<分区>
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;
}
这段代码会造成内存泄漏吗?
arr
位于何处?在堆栈上还是在 RAM 中?
<分区>
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;
}
这段代码会造成内存泄漏吗?
arr
位于何处?在堆栈上还是在 RAM 中?
最佳答案
在这个程序中
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
是函数main的一个局部变量,自动存储时长。它将在函数完成其工作后销毁。
函数本身在调用时分配了数组,并且在退出函数后会被销毁。
没有内存泄漏。
您不得调用 C 函数 free 或 operator delete []。
如果程序看起来像下面这样
int main() {
int *arr = new int[3] {2, 2, 3};
//...
delete [] arr;
return 0;
}
那么你应该写 operator delete [] ,因为它在函数中显示。
关于c++ - 如何在 C/C++ 中释放数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335668/