PDA

View Full Version : where do global variables fall into the memory type?


WhatMeWorry
2006.06.05, 05:19 PM
Ok, I know about stack memory where arguments to functions are
pushed upon entry and popped upon exit. I also understand heap
memory (dynamic memory) where it is allocated and released explicitly
by commands in one's program: malloc/free in C; new/free in C++.

But where do global variables fit into the picture. Is the entire application
considered one big function whose globals are pushed at program startup
and popped at program exit?

And while I'm on the subject, how about static variables in C. They appear
inside a function, but their values are retained from call to call. Are these
in the heap memory since their values are retained?

OneSadCookie
2006.06.05, 05:40 PM
statics are just like globals, except that you can only use their name within a limited scope. Globals are around for the entire life of your program. You can think of them being pushed before main and popped after if you like, though it's not particularly accurate ;)

WhatMeWorry
2006.06.05, 06:35 PM
can think of them being pushed before main and popped after if you like, though it's not particularly accurate

This is cruel. Please. Please tell me. I don't care if my brain explodes with accuracy. Give me details :)

OneSadCookie
2006.06.05, 06:45 PM
Their initial values are stored in a special segment of your application. When the OS loads your application, it decompresses that segment into a particular region of memory. That region is neither part of the heap, nor the stack. When the application exits, all its memory is returned to the OS automatically.