Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack and heap in programming language

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.

like image 463
mingpepe Avatar asked Nov 26 '15 05:11

mingpepe


1 Answers

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.

like image 152
John Bode Avatar answered Dec 09 '22 23:12

John Bode