如何修复 strlen 的 'Conditional jump or move depends on uninitialised value(s)' valgrind 错误?

How to fix 'Conditional jump or move depends on uninitialised value(s)' valgrind error for strlen?

我的目标是将 123456 这样的两位数倒转成 563412。 我正在使用 valgrind 工具检查内存泄漏问题,但是 strlen(reverse_chr) 函数会出现此错误:

Conditional jump or move depends on uninitialized value(s)

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <string>

int main()
{
    char chr[] = "123456";
    char* reverse_chr=(char *) malloc(strlen(chr)+1);
    memset(reverse_chr, 0, strlen(chr));
    int chrlen=strlen(chr);

    for (int t=0; t<chrlen; t+=2)
    {
        reverse_chr[t]=chr[chrlen-t-2];
        reverse_chr[t+1]=chr[chrlen-t-1];
    }
    int len_reverse_chr = strlen(reverse_chr);
    free(reverse_chr);
    return 0;
}

我希望输出没有任何 valgrind 错误。

问题是 reverse_chr 不是有效的字符串,因为它没有正确终止。

char* reverse_chr=(char *) malloc(strlen(chr)+1);
memset(reverse_chr, 0, strlen(chr));

您分配了 7 个字节,但只将前 6 个设置为 0

for (int t=0; t<chrlen; t+=2)
{
    reverse_chr[t]=...
    reverse_chr[t+1]=...

这个 for 循环也只写入 reverse_chr 的前 6 个元素。

int len_reverse_chr = strlen(reverse_chr);

然后这一行试图在 reverse_chr 中找到一个 NUL 字节,但是前 6 个元素不是 '[=20=]' 并且第 7 个元素未初始化(因此 valgrind 抱怨)。

修复:

要么

reverse_chr[chrlen] = '[=13=]';

在循环之后,或者使用calloc:

reverse_chr = static_cast<char *>(calloc(strlen(chr)+1, sizeof *reverse_chr));

这样所有分配的字节都被初始化(你不再需要 memset)。