0

I get this memory issue with valgrind that I cannot make any sense out of. Just adding a line which access the ostream seems to get rid of the memory issue, but that is obviously not the way I want to go. Any ideas what could be wrong? Input to the printBuffer method is a 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)
Joachim
  • 81
  • 1
  • 3
  • 9

1 Answers1

0

Why do you always seem to find the answer as soon as you have asked a question..

I forgot to initialize buf:

char buf[len] = {0};

did the trick.

Joachim
  • 81
  • 1
  • 3
  • 9