views:

101

answers:

1

I have the following in a simple C++ console project in Xcode. When I run this with instrument Leaks, Xcode does not flag any memory leaks even thought there is a glaring one. What is going on ? Any help?

#include <iostream>

int main (int argc, char * const argv[]) {
    // insert code here...

    int *x = new int[20];
    x[0] = 10;
    std::cout << "Hello, World!\n";

    return 0;
}
+2  A: 

There's no leak in your code. For a leak to occur, you have to lose the reference you have to allocated memory. In your case, you do nothing more with the allocated memory, but you still keep a reference to it. Therefore, Leaks thinks you could potentially free it later at some point, and doesn't consider it a leak. (As a reminder, a leak is when you allocate memory, then dispose of the pointer without freeing the memory.)

This program should make Leaks angry:

int main()
{
    int* foo = new int[10];
    foo = NULL;
    sleep(60);
}

As you can see, the address of the memory returned by new int[10] is irremediably lost when foo is overwritten with NULL. Therefore, Leaks should spot it.

Leaks is not a statical analysis tool. It doesn't know what you're gonna do with your pointers. All it knows is that every block of allocated memory is still referenced somewhere.

Leaks is also not a real-time tool. It doesn't find leaks as soon as they occur. Instead, every 10 seconds or so, it freezes the program, scans its memory and tries to find references to all its allocated memory blocks. If it doesn't find any for a specific block, it flags it as a leak. Therefore, if your program's execution lasts less than 10 seconds, obviously Leaks won't find anything helpful.

zneak
@zneak: Thanks. But by that definition, the following code: ``#include <iostream>using namespace std;int* f() { int *x = new int[20]; x[0] = 10; return x;}int main (int argc, char * const argv[]) { // insert code here... f(); std::cout << "Hello, World!\n"; return 0;}`` would be a leak, since we lose reference. Xcode does not flag this as well.
@user231536 It's not a leak either, because `f` is never called. As I told you, Leaks is not a statical analysis tools: it doesn't find potential leaks, it records those that have happened. Since `f` is never called, no leak occured during your program's lifetime.
zneak
Sorry: I missed the call to f(). Even after putting that in, it makes no difference.
@user231536 I should add that Leaks is not real-time. It checks for leaks about every 10 seconds. If you put `sleep(20)` at the end of your code, it should find the leak all right.
zneak
@zneak: Thanks, that was the trick.