c - malloc 分配的数组太长

标签 c malloc

我正在尝试通过包含的代码复制字符串(并使其内容大写):

char* foo(char* word)
{
   int wordLength = strlen(word);
   char* result = (char*)malloc(wordLength * sizeof(char));
   for (int i = 0; i < wordLength; ++i)
      result[i] = toupper(word[i]);
   return result;
}

变量 wordLength包含正确的数字( word 中的确切字母数),但是 result字符串长于 word字符串并在末尾包含几个(大约 4 个)附加字母。

最佳答案

您未能终止复制。

请记住,C 字符串是由数值为 0 的字符终止的字符数组。

更正后的代码:

char * foo(const char *word)
{
  const size_t len = strlen(word);
  char *result = malloc(len + 1);
  char *put = result;
  while(len--)
   *put++ = toupper(*word++);
  *put = '\0';  /* This was missing! */
  return result;
}

这也使用适当的 size_t 类型来处理字符串长度,并简化了内存分配。无需按 sizeof (char)(始终为 1)进行缩放,也无需转换结果的类型。

关于c - malloc 分配的数组太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892159/

相关文章:

c - 解析 C 脚本的输出,valgrind 提示未初始化的值

c - malloc(sizeof(int)) vs malloc(sizeof(int *)) vs (int *)malloc(sizeof(int))

c - 从单链表中删除节点——使用 MALLOC/FREE

C语言中正确释放双链接节点

c - malloc 一个 char[][]

c - c中(0,1)的随机数

c - 为什么在我的代码中使用宏会产生错误?

C - .h 和 .c 文件中的类型冲突

CSV 文件尝试获取每行第一个逗号后的项目

使用第二个参数作为目录复制文件