memory allocation in Stack and Heap

前端 未结 6 506
抹茶落季
抹茶落季 2020-12-08 00:49

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 v

6条回答
  •  臣服心动
    2020-12-08 01:32

    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.

提交回复
热议问题