我有一个字符串,我正在迭代它来寻找一个特定的单词,它恰好位于两个空白之间。
例如:
// where the word that I'm looking for is /docs/index.html
const char* c = "GET /docs/index.html HTTP/1.1rn";
我发现这个词如下;
const char* wbeg = strchr(c, ' ') + 1; // points to '/'
const char* wend = strchr(wbeg, ' ') -1; // points to 'l'
如果我想将该单词存储到另一个位置,我使用strncpy
实现了这个位置
char word[256];
strncpy(word, wbeg, wend - wbeg);
我得到以下错误
在中的0x00007FFAAE8C4A74(基于ucrt.dll)处引发异常ConsoleApplication1.exe:0xC0000005:写入位置时发生访问冲突0x0000000000000000.
当你在文章中展示的要点在一个简单的main()
程序中运行时,。。。
int main()
{
const char* c = "GET /docs/index.html HTTP/1.1rn";
const char* wbeg = strchr(c, ' ') + 1; // points to '/'
const char* wend = strchr(wbeg, ' ') -1; // points to 'l'
char word[256];
strncpy(word, wbeg, wend - wbeg);
printf("%s", word);
return 0;
}
在我的环境中没有发现任何故障。因此,除了发布其余相关代码外,唯一的建议都是确保您没有调用UB。
1) 在您的声明中:
strncpy(word, wbeg, wend - wbeg);
`wend - wbeg` is == 15
而CCD_ 3为16个字符长
将您的对账单更改为:
strncpy(word, wbeg, (wend - wbeg)+1);
2) 从初始化变量开始:
char word[SIZE] = ""
3) strncpy
不以NULL终止。如果要复制到的目标在使用前未初始化,或者在使用后未显式null终止,则可能会发生UB。示例:
char target[]; //contents of target are not guaranteed
char source[]="abcdefghijklmnopqrstuv";
strncpy(target, source, 3);
可以得到以下结果:
|a|b|c|?|?|?|?|?|?|?|?|?|?|?|?|?|...
在哪里?可以是任何东西。
如果要保证ASCII NUL字节位于复制字节的末尾,可以使用以下方法:
strncpy (target, source, 3);
target[3] = 0;
|a|b|c| |?|?|?|?|?|?|?|?|?|?|?|?|...
4) 如果复制发生在重叠的两个对象之间,则行为未定义。在strncpy()
中使用strchr()
函数的结果之前,请确保检查了它们的结果
strncpy
是一个糟糕的函数。如果源比计数参数长,它不会正确终止字符串:
char s[] = "AAAAA";
strncpy(s, "BB", 2);
// s is now "BBAAA", not "BB"
复制后需要显式终止字符串。
char word[SIZE];
ptrdiff_t count = wend - wbeg + 1;
if(count < SIZE) {
memcpy(word, wbeg, count); // might as well use memcpy
word[count] = ' ';
}
else // handle error