我有以下示例代碼模仿應用程序中的代碼。strncpy複製超過指定的大小
#include <iostream>
#include <string.h>
#include <cstring>
#include <atlstr.h>
using namespace std;
void test(char *s, int size)
{
//s = "";
int lens = strlen(s);
char *str1 = "((State:0.000000 Std30c5 = State:T) OR ((State:0.000000 Std30c6 = State:T) OR ((State:0.000000 Std30c7 = State:T) OR ((State:0.000000 Std30c8 = State:T) OR ((State:0.000000 Std30c9 = State:T) OR ((State:0.000000 Std30ca = State:T) OR ((State:0.000000 Std30cb = State:T) OR ((State:0.000000 Std30cc = State:T) OR ((State:0.000000 Std30cd = State:T) OR ((State:0.000000 Std30ce = State:T) OR ((State:0.000000 Std30cf = State:T) OR (...0.000000 = State:T))))))))))))";
int len1 = strlen(str1);
strncpy(s, str1, 512);
int len = strlen(s);
}
int main()
{
char strDisplay[512] = "";
test(strDisplay, 512);
cout << strDisplay << endl;
system("pause");
return 0;
}
結果是: lenofstrtest = 523; lenofstr1 = 512; (狀態:0.000000 Std30c5 =狀態:T)OR((狀態:0.000000 Std30c6 =狀態:T)OR((狀態:0.000000 Std30c7 =狀態:T)或((狀態:0.000000 Std30c8 =狀態:T)
狀態:T)OR((狀態:0.000000 Std30c9 =狀態:T)OR((狀態:0.000000 Std30cc =狀態:T)狀態: T)OR((狀態:0.000000 Std30cf =狀態:T)OR((狀態:0.000000 Std30ce =狀態:T)OR((狀態:0.000000 Std30cf =狀態:T)) )))))))))))ÌÌÌÌJ¢øø)「
爲什麼strncpy複製附加字符?
(這是造成問題,因爲不正確的strnlen導致拆包邏輯就會失控!)
我想這是關係到「strncpy()函數漏洞512個字節」 ......請幫助我理解這個bug。
int len = strlen(strDisplay); cout << len << endl;它的512不是523 – 2014-12-06 11:08:54