我试图理解为什么我的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("nn%dn",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == n",sentences[count]);
}
word[count-starts+1] = ' ';
printf("nn%s",word);
return word;
}
printf
返回:
8 i == ' == m == == a == == b == a == i'm a bau
如果我删除' '
,我得到类似:
'm a ba¨Á£´
在你的代码中
word[count-starts+1] = ' ';
是off-by- 1,基本上,越界访问调用未定义的行为。
你应该把你的代码改成 word[nb_char-1] = ' ';
,因为您已经分配了nb_char
字节,最后一个索引将是nb_char-1
。
也就是说,在使用返回的指针之前,总是需要通过检查NULL
的返回来检查malloc()
是否成功。
如果您删除