Tutorial :Is memory leak caused by global variables?



Question:

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.


Solution:1

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.


Solution:2

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).


Solution:3

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.


Solution:4

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
Previous
Next Post »