【发布时间】:2014-09-13 17:16:32
【问题描述】:
我的 strncat 版本将一个太多字符复制到目标中,我不知道为什么。
#include <stdio.h>
#define MAX_CHARS 20
void nconcatenate(char *start, char *end, int n)
{
if(sizeof start + n > MAX_CHARS)
return;
while(*start++);
start--; /* now points to the final char of start, the \0 */
int i;
for(i = 0; (*start++ = *end++) && i < n; i++);
*start = '\0';
}
int main()
{
char start[MAX_CHARS] = "str";
char *end = "ingy!";
nconcatenate(start, end, 3);
printf("start = %s\n", start);
return 0;
}
使用 3 作为“n”个输出
stringy
这是一个太多的字符。
【问题讨论】:
-
你在调试器中单步调试过代码吗?
-
sizeof start将始终返回sizeof(char*)顺便说一句。 -
@OldProgrammer 我已经尝试过使用 gdb,尽管我仍然是使用它的初学者
-
@EdS。啊,当然,谢谢
-
@EdS。如果我不能以我使用的方式使用 sizeof,我将如何检查 start + n 的大小是否小于 MAX_CHARS?我只能考虑向函数传递另一个参数,但我宁愿不这样做。
标签: c string char off-by-one