Copy bytes to string without memory leak in C++

Viewed 120

How to copy memory bytes to a string variable assigned to a class object with memory leak? The memory holds bytes to be copied (not ends with '\0'), but will be freed later.

The example code is below, and Valgrind all reports memory leak for three cases.

Update: I forget to mention the string variable will be used by another class object.

class Bar
{
   string name;

   ~Bar()
   {
     // should we manually free name's buffer in Bar destructor?    
     // name's buffer is possibly on heap, see Valgrind message
   }
}

void foo(unsigned char *data, uint32 len, Bar *bar)
{
   string str;
   
   // case1, direct conversion
   str = string((char *)data);  
   
   // case2, allocate a new buffer and then copy
   unsigned char *p;            
   p = new unsigned char [len];
   memcpy(p, data, len);
   str = string(char *)p);
   delete[] p;

   // case3, use assign
   str.assign(data, len);   

   // memory leak
   bar->name = str;   
   
}

Valgrind message:

==65558== 96 bytes in 2 blocks are definitely lost in loss record 55 of 128
==65558==    at 0x10012B532: malloc (in /usr/local/valgrind/vgpreload_memcheck-amd64-darwin.so)
==65558==    by 0x1006C3DE0: operator new(unsigned long) (in /usr/lib/libc++abi.dylib)
==65558==    by 0x10063531B: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__grow_by_and_replace(unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long, char const*) (in /usr/lib/libc++.1.dylib)
==65558==    by 0x100634E75: std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::assign(char const*, unsigned long) (in /usr/lib/libc++.1.dylib)

Thank you.

1 Answers

The easiest way to construct a std::string from unterminated data is to use the constructor that takes both a pointer and a length:

string str(reinterpret_cast<const char *>(data), len);

Once you've done that, you can pass around str however you wish without having to worry about leaking memory (str will have made its own internal copy of the data and will take care not to leak it).

Related