您好,我从 valgrind 收到以下错误。
Conditional move based on uninitialized values, Uninitalized values was created by heap allocation.
编译器不会提示。
我在 stackoverflow 上查看了大部分类似的错误,但我似乎无法确定我的错误所在。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int
main(void)
{
char *string1 = malloc(45);
char string2[25] = "HELLO WORLD";
strcpy(string1,string2);
printf("String one is %s\n",string1);
char string3[25];
for (int i = 0; i < 25; i++)
{
string3[i] = tolower(string1[i]);
}
printf("The output is %s\n",string3);
free(string1);
return 0;
}
最佳答案
您的 tolower
调用访问了 string1
指向的内存的前 25 个字节,但只有该内存的前 12 个字节是处于有效状态(感谢 strcpy
)。
您可以使用 calloc
而不是 malloc
来分配具有确定性状态的内存。或者,只复制所需的字节数:
{
const unsigned int M = max(24, strlen(string1));
for (unsigned int i = 0; i != M; ++i)
string3[i] = tolower(string1[i]);
string3[M] = 0;
}
关于基于未初始化值的条件移动,未初始化值由堆分配创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8913562/