簡體   English   中英

Valgrind在調用wcstombs時報告未初始化的值

[英]Valgrind reports uninitialized value when calling wcstombs

我偶然發現了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中報告為未初始化的值。

問題不在您的代碼中。 調用堆棧顯示未初始化的變量在wcstombs實現的內部使用了-您所能做的就是嘗試告訴valgrind不要檢查該庫或從valgrind的輸出中過濾掉這兩個消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM