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

标签 c arrays pointers printf

我想了解为什么我的 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/

相关文章:

c - 如何验证参数是正数?

c++ - 访问静态函数的指针

用于将任意结构从主机字节顺序转换为网络字节顺序的 C 函数?

c - C 中邻接表的图实现

C 窗口 : generate a child process in order to stop and restart (after timeout) the parent process

c# - 如何最大限度地提高 C# 中大数组的按元素操作的性能

javascript - 在javascript中以相同的顺序打乱两个数组

arrays - 数组值的不同排列

c - 如何读取c中的数字列表

c - 如何在 C 上初始化和分配数组到指针