top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to find whether data is stored in stack or its in heap?

+1 vote
548 views
How to find whether data is stored in stack or its in heap?
posted Sep 23, 2014 by Ankur Athari

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Stack and heap both stored in the computer’s RAM (Random Access Memory).

Memory layout of a C program (found on internet)
enter image description here

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.
*/
answer Sep 23, 2014 by Arshad Khan
Similar Questions
0 votes

I found couple of references which show different direction of stack and heap. Is it mandatory, code section always referenced at lower memory address and command line arguments at the higher ? And also I want to know how to figure out direction of stack ?

+6 votes

I was trying to get maximum rectangle area for a given histogram but I used brute force approach which have O(n^2) time complexity so I want some better solution using stack so that we could reduce time complexity to O(n) or O(log n ).

0 votes

It is very basic query but clearing the doubt always make your knowledge stronger.

...