std::string operator+() memory leak?

故事扮演 提交于 2019-12-03 10:53:20

To quote Valgrind FAQ

With GCC 2.91, 2.95, 3.0 and 3.1, compile all source using the STL with -D__USE_MALLOC. Beware! This was removed from GCC starting with version 3.3.

With GCC 3.2.2 and later, you should export the environment variable GLIBCPP_FORCE_NEW before running your program.

With GCC 3.4 and later, that variable has changed name to GLIBCXX_FORCE_NEW.

Also discussed in GCC FAQ

I would not worry too much about STL leaks.

The default STL allocator (for gcc) uses clever tricks to maximize efficiency that Valgrind often reports as leaks. Notably it pools memory, meaning that it keeps memory around when you clear a string and may reuse it next time you insert in a map or a vector for example.

I don't think the pool itself is properly disposed of at the end of the program, probably to avoid the Static Destruction Order Fiasco (ie, imagine that the pool is disposed of and you then request memory, urk). Thus it leaks... right before your program ends and the OS gets the memory back forcefully.

I suspect what's happening is the compiler is using NRVO to put your temporary string into its real return location. That return string is then stored inside an object that's allocated and leaked off the heap.

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