memory allocation in Stack and Heap

This may seem like a very basic question, but its been in my head so:

When we allocate a local variable, it goes into stack. Similarly dynamic allocation cause the variable to go on heap. Now, my question is, is this variable actually lie on stack or heap or we will just a reference in the stack and Heap.

For example,

Suppose I declare a variable int i . Now this i is allocated on the stack. So, when I print the address of i , this will be one of the location on stack? Same question for heap as well.


I'm not entirely sure what you're asking, but I'll try my best to answer.

The following declares a variable i on the stack:

int i;

When I ask for an address using &i I get the actual location on the stack.

When I allocate something dynamically using malloc , there are actually TWO pieces of data being stored. The dynamic memory is allocated on the heap, and the pointer itself is allocated on the stack. So in this code:

int* j = malloc(sizeof(int));

This is allocating space on the heap for an integer. It's also allocating space on the stack for a pointer ( j ). The variable j 's value is set to the address returned by malloc .


Hopefully the following is helpful:

void foo()
{
    // an integer stored on the stack
    int a_stack_integer; 

    // a pointer to integer data, the pointer itself is stored on the stack
    int *a_stack_pointer; 

    // make a_stack_pointer "point" to integer data that's allocated on the heap
    a_stack_pointer = (int*)malloc(10 * sizeof(int));
}

In the case of stack variables, the variable itself (the actual data) is stored on the stack.

In the case of heap allocated memory, the underlying data is always stored on the heap. A pointer to this memory/data may be stored locally on the stack.

Hope this helps.


The pointer variable itself would reside on the stack. The memory that the pointer points to would reside on the heap.

int *i = malloc(sizeof(int));

i would reside on the stack, the actual memory that i points to *i would be on the heap.

链接地址: http://www.djcxy.com/p/82526.html

上一篇: C和malloc中的数组

下一篇: 内存分配堆栈和堆