gpt4 book ai didi

c++ - Valgrind 在调用 wcstombs 时报告未初始化的值

转载 作者:搜寻专家 更新时间:2023-10-31 01:45:17 26 4
gpt4 key购买 nike

我无意中发现了一份我自己无法修复的 Valgrind 报告。我有一个从文件中读取 Microsoft“unicode”字符串(一系列以大小为前缀的两字节对齐的 wchar_t)的函数。示例文件可能如下所示:

0004 0041 0041 0041 0041                 ..A.A.A.A.

以下代码示例从文件中读取“unicode”字符串,并使用 wcstombs 从中生成一个 std::string。

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

#include <boost/shared_array.hpp>
#include <boost/cstdint.hpp>

std::string read_unicode_string(FILE* f)
{
std::wstring s = std::wstring();
wchar_t c;
boost::uint16_t size;
if (2 !=fread(&size, 1, 2, f)) {
return "";
}

// Microsoft's "unicode" strings are word aligned.
for (unsigned int i = 0 ; i < size ; ++i)
{
if (2 != fread(&c, 1, 2, f)) {
break;
}
s += c;
}
s += L'\0';

// Convert the wstring into a string
boost::shared_array<char> conv = boost::shared_array<char>(new char[s.size() + 1]);
memset(conv.get(), 0, sizeof(char) * (s.size() + 1));
wcstombs(conv.get(), s.c_str(), s.size());
return std::string(conv.get());
}

int main(int argc, char** argv)
{
FILE* f = fopen("test", "rb");
if (f == NULL) {
return 1;
}
std::cout << read_unicode_string(f) << std::endl;
fclose(f);
return 0;
}

虽然它似乎确实有效,但 valgrind 报告 wcstombs 中的某些跳跃取决于初始化值:

==8440== Conditional jump or move depends on uninitialised value(s)
==8440== at 0x56606C2: wcsnlen (wcsnlen.c:40)
==8440== by 0x565FCF0: wcsrtombs (wcsrtombs.c:110)
==8440== by 0x56101A0: wcstombs (wcstombs.c:35)
==8440== by 0x401488: read_unicode_string(_IO_FILE*) (test.cpp:32)
==8440== by 0x40157C: main (test.cpp:42)
==8440==
==8440== Conditional jump or move depends on uninitialised value(s)
==8440== at 0x55F2D5B: __gconv_transform_internal_ascii (loop.c:332)
==8440== by 0x565FD41: wcsrtombs (wcsrtombs.c:116)
==8440== by 0x56101A0: wcstombs (wcstombs.c:35)
==8440== by 0x401488: read_unicode_string(_IO_FILE*) (test.cpp:32)
==8440== by 0x40157C: main (test.cpp:42)

我一直在寻找,但我觉得我已经正确地初始化了每个变量。有没有人看到我的代码中的问题?

预先感谢您的帮助!

最佳答案

这是一个严重的错误!如果sizeof(wchar_t)大于 2(比方说 4),宽字符串“s”将获得 (2) 个未初始化的字节,这些字节在 wcstombs 中报告为未初始化的值.

关于c++ - Valgrind 在调用 wcstombs 时报告未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22375847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com