我正在尝试通过包含的代码复制字符串(并使其内容大写):
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/