How to free an array in C/C++ [closed]

有些话、适合烂在心里 提交于 2020-01-02 04:38:27

问题


int main() {
    // Will this code cause memory leak?
    // Do I need to call the free operator?
    // Do I need to call delete?
    int arr[3] = {2, 2, 3};
    return 0;
}
  1. Does this code create a memory leak?

  2. Where does arr reside? On the stack or in RAM?


回答1:


In this program

int main() {
    // Will this code cause memory leak?
    // Do I need to call the free operator?
    // Do I need to call delete?
    int arr[3] = {2, 2, 3};
    return 0;
}

array arr is a local variable of function main with the automatic storage duration. It will be destroyed after the function finishes its work.

The function itself allocated the array when it was called and it will be destroyed afetr exiting the function.

There is no memory leak.

You shall not call neither C function free nor the operator delete [].

If the program would look the following way

int main() {
    int *arr = new int[3] {2, 2, 3};
    //...
    delete [] arr;
    return 0;
}

then you should write operator delete [] as it is shown in the function.




回答2:


The stack is in RAM.

No, it doesn't leak memory. Yes, the array will normally be "on the stack" (i.e., wherever the implementation allocates local variables, which is required to have stack-like behavior, even though the hardware might not provide direct support for a stack).




回答3:


You have to call free only for objects you have created with malloc, and delete for those you've created with new.

In this case you don't need to do anything, this variable is managed automatically. As soon as it goes out of scope (i.e., in this case at the end of main()) its memory will be freed automatically.

So:

  1. No, there are no memory leaks here.
  2. The question doesn't make much sense. All variables are in RAM. The stack is just a special part of the RAM memory, which is managed in a way that results fast and efficient to deal with function calls, automatic allocation/deallocation of local variables, etc. Anyway, yes, arr is created on the stack, whereas variables created using malloc or new are said to be on the "free store" or "heap".



回答4:


No memory leak is caused since arr is a local variable (and is therefore located on the stack) and goes out of scope when the closing curly brace of main is reached. This implies the absence of the need to call free or delete.

You seem to misunderstand the term "RAM." It just means "Random Access Memory", which can refer to every kind of randomly accessible memory, commonly a PC's main memory. The stack is just as well part of RAM as the free store or (runtime part of ) the OS is.



来源:https://stackoverflow.com/questions/33335668/how-to-free-an-array-in-c-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!