繁体   English   中英

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

[英]C: printf char* return weird last 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("\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'则会得到类似以下内容:

  'ma ba¨Á£´ 

在你的代码中

   word[count-starts+1] = '\0';

一对一的 ,基本上,越界访问会调用未定义的行为

您应该将代码更改为

   word[nb_char-1] = '\0';

因为,您已经分配了nb_char个字节,而最后一个索引将是nb_char-1

也就是说,在使用返回的指针之前,始终需要通过检查针对NULL的返回来检查malloc()是否成功。

如果删除\\0 printf无法知道字符串结束,并且将不断增加指针,直到看到空值为止,并且冒着出现分段错误的风险。

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

另外,对于您要实现的目标,还有memcpystrncpy

有关更多详细信息,请参见手册页。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM