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

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

    That is a very good question, while many would answer it is the difference between stack and heap allocation, the fundamental answer is the under lying system has exposed something to you that it shouldn't.

    When you allocate memory, you shouldn't have to worry about giving it back. The system should be smart enough to figure out that you have no access (point or reference) to it any more, therefore it can automatically take the memory back.

    Newer languages like Java and C# have done this.

提交回复
热议问题