Valgrind reports memory leak when assigning a value to a string

那年仲夏 提交于 2019-11-28 11:06:58

Because you call exit(0), so the string destructor is never invoked. Just use return 0.

To elaborate, the constructor of std::string allocates heap memory to store the string, relying on the destructor to deallocate that memory. If you declare a string object on the stack, the destructor will automatically be invoked when the string object goes out of scope, thus freeing the memory. But exit is really a C mechanism; it immediately exits the program without performing stack-unwinding meaning that C++ destructors for local stack objects will not be called.

If you allocate five strings, do you get five times the memory leak, or is it still the same amount? If it's the same amount, then you probably don't have a leak at all. Some libraries allocate memory for internal bookkeeping/efficiency/et cetera that doesn't get released until after valgrind stops looking. These get picked up as memory leaks because your program caused the allocation but never caused a deallocation. If it's five times the amount, then your implementation of string may be at fault. I agree with Charles Salvia though... try again with return 0; instead of exit(0); and see if that changes anything.

Nate Glenn

In one of my computer science classes we were told that Valgrind outputs information about strings that we shouldn't worry about. Here's the suppression file that they gave us for strings: https://sites.google.com/site/complingfiles/files/string.supp

Despite having no exit(0) at the end of program I had similar problem with false positives with std::string . I was statically linking with libstdc++. Switching linking option to shared and compiling with GLIBCXX_FORCE_NEW suppressed the warnings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!