我该如何修复valgrind未初始化的值错误?

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

我编写了一个小应用程序,它可以在某些时候使用二进制数据。在单元测试中,我将这些数据与预期数据进行比较。发生错误时,我希望测试显示十六进制输出,例如:

Failure
      Expected: string_to_hex(expected, 11)
      Which is: "01 43 02 01 00 65 6E 74 FA 3E 17"
To be equal to: string_to_hex(writeBuffer, 11)
      Which is: "01 43 02 01 00 00 00 00 98 37 DB"

为了显示它(并首先比较二进制数据),我使用the code from Stack Overflow,根据我的需要稍微修改它:

std::string string_to_hex(const std::string& input, size_t len)
{
    static const char* const lut = "0123456789ABCDEF";

    std::string output;
    output.reserve(2 * len);
    for (size_t i = 0; i < len; ++i)
    {
        const unsigned char c = input[i];
        output.push_back(lut[c >> 4]);
        output.push_back(lut[c & 15]);
    }

    return output;
}

在使用qazxsw poi检查内存泄漏时,我发现了很多错误,例如:

使用大小为8的未初始化值 在0x11E75A:string_to_hex(std :: __ cxx11 :: basic_string,std :: allocator> const&,unsigned long)

我不太明白这一点。首先,一切似乎已初始化,包括,我错了,valgrind。而且,代码中没有提到大小8; output的值因测试而异,而len每次报告的大小相同。

我该如何解决这个错误?

c++ memory-management memory-leaks
1个回答
1
投票

因此,这是将指向valgrind的指针传递给char类的邪恶隐式构造函数的指向缓冲区的情况之一,导致字符串被截断为第一个std::string。直接的方法是传递一个原始指针,但更好的解决方案是开始使用\0 array_view或类似的实用程序类,它们将至少在spaninput的调试版本中提供索引验证。

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