Reputation: 559
In C99, the following line of code create a variable ptr on stack which points to a memory region on the heap.
int *ptr = (int*)malloc(sizeof(int)*10);
Where are the definitions of stack and heap? I could not find them in the C99 language specification.
Are the stack and heap defined by the operating system or instruction set architecture or something else?
The another related questions is that whether the concept of stack and heap in C# are exactly the same as the concept in C99? Since C# code are run on the .Net framework, I do not sure if the concept is the same as C99.
Upvotes: 7
Views: 493
Reputation: 123458
Stacks and heaps are implementation details; like you discovered, the C language definition doesn't mention them at all.
The C language definition talks about storage durations of objects. Objects with auto
storage duration have lifetimes that extend over their enclosing block; it just so happens that the hardware stack makes that behavior easy to implement, so almost all C implementations do so. Objects with allocated
storage duration have lifetimes that extend from the malloc
/calloc
/realloc
call until a call to free
. Again, almost all C implementations take advantage of the system heap for that behavior.
However, an implementation doesn't have to use a system-supplied stack or heap to satisfy object storage duration requirements; it would just be a bit more work.
Upvotes: 6
Reputation: 596
The heap is the amount of memory that is allocated to a given process that is running on the machine. The stack is a generally smaller amount of memory that is allocated to the thread that is currently running on the given process.
When you create a local variable it is stored to the stack. This selection of memory is called the stack because as it deals with scopes different values are pushed or popped from the addressable space as you would do with a stack data structure.
Then when you malloc a variable it is stored to the heap and thus saved even across multiple scopes.
Note that things stored on the heap must be free'd when you're done using them, whereas the OS automatically handles that for things on the stack.
checkout http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html
Upvotes: 1