我想了解为什么我的 printf()
char* extract_word()
{
char* sentences = "hi! i'm a banana!";
int starts = 4;
int ends = 12;
int count;
int nb_char = ends-starts+1;
char* word = malloc(nb_char);
printf("\n\n%d\n",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
}
word[count-starts+1] = '\0';
printf("\n\n%s",word);
return word;
}
printf
返回:
8 i == ' == m == == a == == b == a == i'm a bau
如果我删除 '\0'
我会得到类似的东西:
'm a ba¨Á£´
最佳答案
在你的代码中
word[count-starts+1] = '\0';
是off-by-one基本上,越界访问会调用 undefined behavior .
您应该将代码更改为
word[nb_char-1] = '\0';
因为,您已经分配了 nb_char
字节,最后一个索引将是 nb_char-1
。
也就是说,在使用返回的指针之前,总是需要通过检查返回值是否为 NULL
来检查 malloc()
是否成功。
关于C: printf char* 返回奇怪的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39703703/