Valgrind错误涉及未初始化的字符串:错误标志?

问题描述 投票:0回答:2

[当运行valgrind来检查用C89 / 90编写的程序中的错误时,尽管已初始化了字符串,但我编写的Uninitialised value was created by a heap allocation函数却出现了strToUpper()错误。

我正在使用此函数来比较忽略大小写的字符串。不幸的是,C89似乎没有在strcasecmp()中包含<string.h>函数,因此我编写了自己的函数,称为strToUpper()strcmp()函数。

CODE

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;
}

VALGRIND ERROR

==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)

有什么想法吗?

valgrind c89
2个回答
0
投票

您不终止复制的字符串。


0
投票

而不是始终使用malloc(blah),而不是使用calloc(1,blah)。后者将所有分配的内存设置为零。

© www.soinside.com 2019 - 2024. All rights reserved.