Search code examples
c++xcodememory-leaksinstrumentsxcode4.5

Instruments does not catch undeleted objects when program terminates


For the sake of demonstration, I have created this simple console application:

#include <iostream>

class Person {
public:
    int mAge;
};

int main(int argc, const char * argv[])
{
    Person *iPerson = new Person();
    iPerson->mAge = 15;

    std::cout << "Age: " << iPerson->mAge;
    return 0;
}

Now I'm aware that Valgrind and CPP Check will identify leaks here, but testing Apple's Instruments, When I profile this code I can't see any leaks. This is despite iPerson never being deleted.


Solution

  • Leaks Instrument performs snapshots at a predefined frequency. By default, that value is "every 10 seconds". You program completes before 10 seconds. Thus, the leak is never collected. So you must suspend execution after iPerson has gone out of scope in order for that leak to be detected. Also, if you just add a sleep while that pointer is still referenced on the stack or in a register, then it won't be a leak.