printf char*返回奇怪的最后一个字符



我试图理解为什么我的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()是否成功。

如果您删除 printf没有办法知道字符串结束,并将继续增加指针,直到它看到一个空值,你承担的风险得到分段错误。

对于末尾没有0的字符串,可以使用snprintf

还有memcpystrncpy

查看手册页了解更多详细信息

最新更新