使用valgrind的ostringstream / ostream存在奇怪的内存问题

时间:2018-03-22 16:59:30

标签: valgrind ostream ostringstream

我从valgrind得到这个内存问题,我无法理解。只是添加一条访问ostream的行似乎摆脱了内存问题,但这显然不是我想要的方式。什么想法可能是错的? printBuffer方法的输入是std :: ostringstream。

#define FORMATSTRWBUF(pos, buf, len, ...) pos += snprintf(buf + pos, len - pos, __VA_ARGS__)

void printBuffer(std::ostream& os, const char* buffer_name, const unsigned char* buffer, int length) const {
    os << buffer_name;
    os << "{length ";
    os << length;
    os << ", contents 0x";
    // If this line is here, there is no memory issues, but...
    fprintf(stdout, "\n%s %s\n", buffer_name, static_cast<std::ostringstream&>(os).str().c_str());
    // fprintf(stdout, "\n%s\n", buffer_name);  // having this line only has no effect
    int pos = 0;
    const int len = 1024;
    char buf[len];
    for (int32_t i = 0; i < length; ++i) {
        FORMATSTRWBUF(pos, buf, len, "%02X", buffer[i]);
    }
    //... if it is not there is a "Conditional jump or move depends on uninitialised value(s)" memory issue here:
    os << buf;
    os << "}";
  }

==43066== Conditional jump or move depends on uninitialised value(s)
==43066==    at 0x4C2C129: strlen (vg_replace_strmem.c:454)
==43066==    by 0x5687378: length (char_traits.h:263)
==43066==    by 0x5687378: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (ostream:562)
==43066==    by 0x44D462: printBuffer(std::ostream&, char const*, unsigned char const*, int) const (message.h:102)

1 个答案:

答案 0 :(得分:0)

为什么在你提出问题后,你似乎总能找到答案。

我忘了初始化buf:

char buf[len] = {0};

做了这个伎俩。