使用strncpy复制字符串时遇到异常
我有一个字符串,我正在迭代寻找一个特定的单词,它恰好位于两个空格之间 例如:使用strncpy复制字符串时遇到异常,c,pointers,exception,strncpy,C,Pointers,Exception,Strncpy,我有一个字符串,我正在迭代寻找一个特定的单词,它恰好位于两个空格之间 例如: // where the word that I'm looking for is /docs/index.html const char* c = "GET /docs/index.html HTTP/1.1\r\n"; 我发现这个词如下 const char* wbeg = strchr(c, ' ') + 1; // points to '/' const char* wend = strchr(wbeg, '
// where the word that I'm looking for is /docs/index.html
const char* c = "GET /docs/index.html HTTP/1.1\r\n";
我发现这个词如下
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);
我得到以下错误
在中的0x00007FFAE8C4A74(ucrtbased.dll)处引发异常
ConsoleApplication1.exe:0xC0000005:访问冲突写入位置
0x0000000000000000
strncpy
是一个蹩脚的函数。如果源长度大于计数参数,则不能正确地nul终止字符串:
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] = '\0';
}
else // handle error
char字[SIZE];
ptrdiff_t count=wend-wbeg+1;
如果(计数<大小){
memcpy(word、wbeg、count);//最好使用memcpy
字[计数]='\0';
}
else//句柄错误
当您在帖子中展示的要点在一个简单的main()
程序中运行时
int main()
{
const char* c = "GET /docs/index.html HTTP/1.1\r\n";
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;
}
…在我的环境中未发现任何故障。因此,除了发布其余相关代码之外,唯一的建议都是确保您没有调用
1) 在你的声明中:
strncpy(word, wbeg, wend - wbeg);
`wend - wbeg` is == 15
而/docs/index.html
的长度为16个字符。将您的声明更改为:
strncpy(word, wbeg, (wend - wbeg)+1);
2) 从初始化变量开始:
char word[SIZE] = ""
3) strncpy
不为空终止。如果要复制到的目标在使用前未初始化,或者使用后未显式为null终止,则可能会发生这种情况。
例如:
可以得到以下结果:
|a|b|c|?|?|?|?|?|?|?|?|?|?|?|?|?|...
在哪里?什么都可以
如果要确保ASCII NUL字节位于复制字节的末尾,可以使用以下方法:
strncpy (target, source, 3);
target[3] = 0;
|a|b|c|\0|?|?|?|?|?|?|?|?|?|?|?|?|...
4) 如果复制发生在重叠的两个对象之间,则行为未定义。在
strncpy()
中使用函数结果之前,请确保正在检查strchr()
函数的结果。是否检查strchr()
的返回是否为NULL
?char-word[256]代码>-->字符字[256]=“”代码>,strncpy(word,wbeg,wend-wbeg)代码>-->strncpy(word、wbeg、wend-wbeg+1)
@stanna:如果代码在函数之前中断,为什么不发布相关代码?是时候学习如何使用调试器了。提供的代码不会出错。当然,在strncpy()
之后使用word
会失败并导致“访问冲突写入位置0x0000000000000000”。投票结束,因为这篇文章缺少“复制所需的最短代码”,他说他在调用strncpy时出错。他没有显示他是否以零结束,所以你只是在猜测。strncpy也不是“垃圾”;它只是按照指定的方式运行。@PaulOgilviestrncpy
可能会按照指定的方式运行,并且对于它的用途来说可能很方便。但是它的名字好吗?它适合一般用途吗?它应该包含在标准库中吗?答案是否定的,否定的,否定的。
strncpy (target, source, 3);
target[3] = 0;
|a|b|c|\0|?|?|?|?|?|?|?|?|?|?|?|?|...