memory allocation in Stack and Heap

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.


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.