Strdup with stringstreams causes valgrind errors

I have the following problem: I am writing a C ++ program that should wrap around the C library, so when I interact with the library, I always need to use char*instead std::stringfor all operations. To avoid working as much as possible with char*, I do formatting with strings, for example, as follows:

#include <iostream>
#include <sstream>
#include <string.h>
#include <cstdlib>

using namespace std;

int main(int argc, char** argv)
{
  ostringstream str;

  str << argv[0] << "+" << "hello";

  const char *s = str.str().c_str();

  char *y = strdup(s);

  // this I would give to a library function

  cout << y << endl;

  free(y);

  return 0;
}

As for the exit, the program correctly displays "./test+hello". However valgrind gives me a lot of errors like

==30350== Invalid read of size 1
==30350==    at 0x402B858: __GI_strlen (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30350==    by 0x4213475: strdup (in /usr/lib/libc-2.16.so)
==30350==    by 0x41B2604: (below main) (in /usr/lib/libc-2.16.so)
==30350==  Address 0x4341274 is 12 bytes inside a block of size 25 free'd
==30350==    at 0x4029F8C: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==30350==    by 0x410387A: std::string::_Rep::_M_destroy(std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.17)
==30350==    by 0x41B2604: (below main) (in /usr/lib/libc-2.16.so)

What am I doing wrong?

+5
source share
1 answer
 const char *s = str.str().c_str();

str() . c_str, . .

:

std::string s = str.str();
const char* s = s.c_str()

, .

+6

All Articles