[当运行valgrind来检查用C89 / 90编写的程序中的错误时,尽管已初始化了字符串,但我编写的Uninitialised value was created by a heap allocation
函数却出现了strToUpper()
错误。
我正在使用此函数来比较忽略大小写的字符串。不幸的是,C89似乎没有在strcasecmp()
中包含<string.h>
函数,因此我编写了自己的函数,称为strToUpper()
和strcmp()
函数。
char* strToUpper(char* inStr)
{
int i;
char *upperStr;
size_t strLen = strlen(inStr);
upperStr = (char*)malloc(sizeof(char) * (strLen + 1));
/* Does this for loop not initialise upperStr? */
for (i = 0; i < strLen; i++)
upperStr[i] = toupper(inStr[i]);
return upperStr;
}
==27== Conditional jump or move depends on uninitialised value(s)
==27== at 0x4C31FAA: strcmp (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27== by 0x406649: strcasecmp (stringPlus.c:178)
==27== ...
==27== by 0x400FEB: main (main.c:58)
==27== Uninitialised value was created by a heap allocation
==27== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==27== by 0x4062E4: strToUpper (stringPlus.c:58)
==27== by 0x406622: strcasecmp (stringPlus.c:175)
==27== ...
==27== by 0x400FEB: main (main.c:58)
有什么想法吗?
您不终止复制的字符串。
而不是始终使用malloc(blah)
,而不是使用calloc(1,blah)
。后者将所有分配的内存设置为零。