std::string memory leak

巧了我就是萌 提交于 2019-12-10 14:57:02

问题


I've got this class AppController and the function connectPlayer:

/* AppController.h */
    class AppController
    {
          // Some other declarations ...
      private:
            static const string TAG;
    };

/* AppController.cpp */

#include "AppController.h"
const string AppController::TAG = "AppController";

AppController::AppController() {
    /* some code here...*/
}

void AppController::connectPlayer() {
    std::string port;
    std::string host;
    port = CM->getMenu()->getData("PORT");
    host = CM->getMenu()->getData("HOST");
    this->setState("Connecting...");
    Logger::info(TAG, "Port: " + port);
    Logger::info(TAG, "Host: " + host);
}

And when I execute the program, I get this from valgrind:

==7848== 25 bytes in 1 blocks are definitely lost in loss record 160 of 671
==7848==    at 0x402842F: operator new(unsigned int) (vg_replace_malloc.c:255)
==7848==    by 0x4210A83: std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==7848==    by 0x4212CF7: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==7848==    by 0x4212E65: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/i386-linux-gnu/libstdc++.so.6.0.16)
==7848==    by 0x8080501: AppController::connectPlayer() (in /home/maine/Escritorio/taller7542/UltimaVersion/src/main)

Any ideas? Thank you in advance!


回答1:


You have std::string objects in global scope: AppController::TAG.

When application finished in not very normal way you've got these kind of valgrind errors for global objects. Probably nothing to worry.

If you (cannot/don't want to) change your program - read this doc: http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress to get rid of this very error.




回答2:


Sometimes, valgrind gives false positives. This means that even if valgrind says you lose memory, actually you don't.

The only thing to worry about is when you call the exit() function, as explained in this question.

If you do not want to see these warnings any more, you can create a suppressions file giving valgrind some information on which errors to ignore.




回答3:


I had seen this issue once when I had a string in a class in global scope. Valgrind kept complaining that I was leaking memory. I just "deleted" the object at exit and the error was gone.



来源:https://stackoverflow.com/questions/13001784/stdstring-memory-leak

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