Tutorial :Is memory leak caused by global variables?


When I checked my application for memory leaks it is showing 12 leaks. What will be the effect of this?

I used global variables as shown below

#import "file1.m"    int num;    #import "file2.m"    extern int num;  num = 10;  

Can this cause memory leaks?

Anyone please help. I am a beginner in programming.


I very much doubt it. Memory leaks are dynamic allocations (in other words, run-time allocation rather than compile-time) where you forget to free them. Global variables like num are supposed to exist for the duration of the executable so they should not be considered a leak.

I suspect you'll have to look elsewhere.

Perhaps if you posted the output from your leak checker, we could help out some more.


No, you do not allocate any dynamic memory here and so it (most definitely) cannot leak.

If you run your application with "Leaks" tool you can see the line where leak occurs - there's "Extended details" button at the bottom of the window that shows call stack where memory actually leaks (or suspected to leak).


Having a global int around should not count as or cause a memory leak. A more typical global-counted-as-memory leak is if you have a global pointer to a singleton object that gets initialised once and then hangs around for the lifetime of the process. These show up as memory leaks even though they technically aren't.

The only leaks I would be concerned about are related to non-global, non-static variables as these tend to be "real" leaks.


Do you have XCode 3.2? Maybe you have a look at the static analyzer (Build and Analyze). It often helps you with finding memory leaks.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »