cubic1271
cubic1271

Reputation: 1138

valgrind & C++ : building std::string from character buffers

Simple C++ / valgrind question I'm hoping somebody can help out with.

When running valgrind against the following code, I get two possible leaks related to std::string :

==10325== 17 bytes in 1 blocks are possibly lost in loss record 1 of 2
==10325==    at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==10325==    by 0x40CFD05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0B10: ??? (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0CF5: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x804872B: main (test.cc:9)
==10325== 
==10325== 17 bytes in 1 blocks are possibly lost in loss record 2 of 2
==10325==    at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255)
==10325==    by 0x40CFD05: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D0977: std::string::_Rep::_M_clone(std::allocator<char> const&, unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D17AC: std::string::reserve(unsigned int) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D1C7F: std::string::append(std::string const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x40D1D63: std::string::operator+=(std::string const&) (in /usr/lib/libstdc++.so.6.0.13)
==10325==    by 0x804879D: main (test.cc:11)

While it wouldn't be too much work to suppress them, and the code seems straightforward enough to me, I'd like to be sure I'm not missing something obvious here before I try to convince valgrind that I know what I'm doing.

#include <stdio.h>
#include <stdlib.h>
#include <string>

int main(int argc, char *argv[])
{
        char buffer[8192];
        sprintf(buffer, "ABCD");
        std::string str(buffer);
        std::string str2 = "";
        str2 += str;
        exit(EXIT_SUCCESS);
}

Upvotes: 2

Views: 2828

Answers (2)

Kibbick
Kibbick

Reputation: 216

Note also that if you are using libstdc++ (the standard c++ library for Linux and some BSDs), you should compile your program with GLIBCXX_FORCE_NEW, to disable std::string memory pool optimizations, which look like leaks to valgrind. Remember to turn that back off for your release builds :-).

Upvotes: 7

sth
sth

Reputation: 229754

Terminating the program by calling exit() is not really an orderly shutdown, it basically aborts the program at the current place. Therefore str and str2 are not destroyed before program termination and valgrind picks up on that.

When you exit the program normally by just returning from main, the destructors for str and str2 should get called and the reported "memory leaks" should go away.

Upvotes: 7

Related Questions