Hey guys, I'm trying to learn more about exactly what C stores on the stack, what it stores on the heap and what is considered global data etc. So any help is greatly appreciated. For example:
This is a global variable (not inside a function). Would this be stored on the code/global data memory image section? Or would this go on the stack?Code:int x = -2;
Another question:
Is the variable b on the stack even though it's a formal parameter and not an actual? Or would it not be pushed onto the stack until used in the return statement of return b - x;?Code:int f(int b) { return b - x; }
Thanks for any help guys!
The heap is used to store memory allocated using malloc(). It is accessed using pointers.
The stack stores pretty much everything else.
Global variables exist from the time the program starts until it ends, unlike other variables that are created/destroyed on the stack as they enter/leave scope.
That's true, but you didn't mention data segments. Static data (string constants,etc.) and global variables are stored in data segments that are separate from the stack and code segments. All local variables are stored on the stack. Note that when things are allocated with new or malloc, the pointer to the object is local, but the physical bytes comprising that object are stored on the heap.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks