Stack and heap both stored in the computer’s RAM (Random Access Memory).
Memory layout of a C program (found on internet)
1.Stack segment is used to store all local variables.
example:
void func()
{
int a;
char b;
int *x;
}
/*
Here in the above function all a, b , x are stored in the stock segment.
And the memory allocation took place at the run time only, means when you are calling this function
the memory got allocated for the local variables and deleted when exiting the fucntion.
*/
2.Heap segment is assigned to dynamically allocated variables. In C language dynamic memory allocation is done by using malloc and calloc functions.
example:
void function()
{
char *temp;
temp = malloc(100 * sizeof(char));
// Perform operation on temp..
free(temp);
}
/*
NOTE: In stack segment there is no need of freeing/deleting the allocated memory, its taken care by the C compiler.
But for the heap segment memory after using it you have to free it before exiting. So that, that memory area can be used by the other programs.
*/