C++'s std::string pools, debug builds? std::string and valgrind problems

前端 未结 6 663
旧巷少年郎
旧巷少年郎 2021-01-11 16:38

I have a problem with many valgrind warnings about possible memory leaks in std::string, like this one:

120 bytes in 4 blocks are possibly lost in loss recor         


        
6条回答
  •  误落风尘
    2021-01-11 17:04

    I just had this problem and for me, it was because I was linking with a development version of a library, but my test code was picking up the older system-installed version. The changes were subtle enough that it would link and run without any apparent problems, but Valgrind would detect weird leaks. Using ldd in place of valgrind confirmed that it was picking up the wrong library file. Setting LD_LIBRARY_PATH correctly fixed it, although the correct solution is to increment the library version as it's obviously not backwards compatible any more if you get this happening.

    I have also seen this problem when an object hasn't been destroyed properly, such as a class with virtual functions missing a virtual destructor. When the class is put into a pointer-to-base-class and then destroyed, only the base class destructor runs, leaking anything allocated in the derived classes, like std::string instances in your example. The hint here was to check which class was using the leaked string, and follow the class hierarchy back to the base class and confirm it has an explicit virtual destructor, even an empty one. I was assuming they were implicit if there are virtual functions in a class but apparently not, and GCC doesn't warn you about this.

提交回复
热议问题