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

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

    Because the language let's you pick between the stack and the heap.

    Reasons why you'd want to pick between the stack and the heap:

    • Variables on the heap purposely do not free themselves so that you can use them past the scope of your code block or function.
    • It is more efficient to work with the stack compared to the heap
    • On most compilers you cannot pick the size of an object or array on the stack at runtime, so the heap would be used here.

    Why the heap can't be automatically freed:

    Because there is no way to know when you are done with the memory. There are ways to emulate garbage collection, but this involves when you have no more variables on the stack and heap holding a pointer to the data on the heap.

    More on Stack vs Heap:

    The C language let's you chose whether you want to define your variables on the stack or the heap.

    • Variables on the stack are automatically freed when they fall out of scope.
    • Variables on the heap are not automatically freed.

    malloc create variables on the heap. A simple declaration such as int x; creates a variable on the stack.

    See further reading on stack vs heap in my answer here.

    Pointers:

    Just to clarify: Pointer varaibles are created on the stack and they hold a memory address to the data allocated on the heap. They take 4 bytes on the stack on a 32-bit system and 8 bytes on the stack on a 64-bit system.

提交回复
热议问题