Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Valgrind not detecting memory leak after QObject connected



  • Hello, I'm new to using Valgrind and wanted to use it in a large project. Before that, I wrote a simple test to create a memory leak on purpose and see the output. But I failed to do so in a very specific case. When a QObject is created using new then connected via a signal/slot mechanism, Valgrind fails to detect it even if delete is not called !

    7  int main(int argc, char *argv[])
    8  {
    9    QCoreApplication app(argc, argv);
    10
    11    Test* t = new Test();
    12
    13   /* Memory leak detected by Valgrind */
    14    QTimer* timer_1 = new QTimer();
    15
    16    /* Memory leak NOT detected by Valgrind */
    17    QTimer* timer_2 = new QTimer();
    18    QObject::connect(timer_2, SIGNAL(timeout()), t, SLOT(timeoutSlot()));
    19
    20    /* Memory leak detected by Valgrind */
    21    QTimer* timer_3 = new QTimer();
    22    QObject::connect(timer_3, SIGNAL(timeout()), t, SLOT(timeoutSlot()));
    23    QObject::disconnect(timer_3, SIGNAL(timeout()), t, SLOT(timeoutSlot()));
    24
    25    return 0;
    26 }
    

    Test is a simple QObject subclass with one slot doing nothing.
    And here is what Valgrind output looks like:

    144 (32 direct, 112 indirect) bytes in 1 blocks are definitely lost in loss record 33 of 39 | Location main.cpp:14
    376 (32 direct, 344 indirect) bytes in 1 blocks are definitely lost in loss record 36 of 39 | Location main.cpp:21
    504 (16 direct, 488 indirect) bytes in 1 blocks are definitely lost in loss record 37 of 39 | Location main.cpp:11
    

    As you can see, memory leak on line 17 does not appear.

    If possibly some memory leak escapes valgrind output, how can I make sure this does not happen in a larger project with many new, connect, etc ?

    For the setup, I'm using QtCreator and the default Valgrind installation, no specific parameters were introduced.

    Thank you


  • Lifetime Qt Champion

    int main(int argc, char *argv[])
    {
      QCoreApplication app(argc, argv);
    
      /* Memory leak detected by Valgrind */
      QTimer* timer_1 = new QTimer();
    
      /* Memory leak NOT detected by Valgrind */
      QTimer* timer_2 = new QTimer();
    
      /* Memory leak detected by Valgrind */
      QTimer* timer_3 = new QTimer();
    
      return 0;
    }
    

    With this code valgrind properly shows 3 memleaks.


Log in to reply