c++ - 如何在 C/C++ 中释放数组

标签 c++ c memory-management memory-leaks

<分区>

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. 这段代码会造成内存泄漏吗?

  2. 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/

相关文章:

c++ - 通过引用 vector 给出错误的结果

c++ - C 和 C++ 中类型的互操作性

python - 如何应用最大缓存大小来内存?

c++ - 当 vector 需要更多内存并分配内存时,指针会发生什么变化?

c++ - 错误: variable length array of non-POD element type 'string' (aka 'basic_string<char>' )

c++ - OpenMP C++ GCC 基本例程

c++ - wchar_t 到 unsigned char 的转换

c - 检查字符串中的字符是否为特定形式的函数

c - 下面的链接列表代码给出了有趣的错误,你能检查一下吗?

iphone - 我的应用程序崩溃了,但除了数据格式化程序暂时不可用的行之外没有显示任何内容,我现在应该做什么?