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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With