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

前端 未结 8 1246
既然无缘
既然无缘 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:26

    You don't always have to use free on a pointer, just ones declared with malloc. You can declare a pointer that points to a memory location on the stack

    int a = 3;
    int* p = &a;
    

    and this memory (along with the pointer) will also be automatically disposed of when it goes out of scope. Using malloc allocates the same memory on the heap, so you have to handle cleanup manually.

提交回复
热议问题