【发布时间】:2015-02-04 12:14:24
【问题描述】:
我有以下模仿应用程序代码的示例代码。
#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;
strtest = "((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 )) )))))))))ÌÌÌÌJ¢Š£øø)"
为什么 strncpy 会复制额外的字符?
(这会导致问题,因为不正确的 strnlen 会导致解包逻辑失控!)
我猜这与“strncpy bug 512 bytes”有关...请帮助我理解这个错误。
【问题讨论】:
-
int len = strlen(strDisplay); cout