Why do I have to use free on a pointer but not a normal declaration?

前端 未结 8 1235
既然无缘
既然无缘 2021-02-13 20:07

Why do I have to use free() when I declare a pointer such as:

int *temp = (int*)malloc(sizeof(int))
*temp = 3;

but not when I do:



        
8条回答
  •  你的背包
    2021-02-13 20:25

    Normal declarations are put on the stack. When the function returns the stack pointer reverts to the value it had before the function was called, so the memory is automatically reclaimed.

    Malloc-based declarations are allocated from the 'heap', which requires the programmer to manage allocations and deallocations.

提交回复
热议问题