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;
}
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.