如何在C/C ++中释放数组 [英] How to free an array in C/C++

查看:135
本文介绍了如何在C/C ++中释放数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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. 此代码是否会造成内存泄漏?

  1. Does this code create a memory leak?

arr驻留在哪里?在堆栈上还是在RAM中?

Where does arr reside? On the stack or in 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的局部变量,具有自动存储持续时间.该函数完成工作后将被销毁.

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.

没有内存泄漏.

您既不能调用C函数,也不能调用操作符delete [].

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;
}

然后,您应该编写操作符delete [],如函数中所示.

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

这篇关于如何在C/C ++中释放数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆