如何使用delete []运算符清除动态分配的内存? (无法使用常规删除语法清除)

问题描述 投票:1回答:3

我使用int * p = new int [size]分配了一个动态内存;现在当我尝试使用delete [] p删除它时;我在执行代码时遇到了分段错误(核心转储)。

最初我能够动态输入数组元素并且它正常工作。但是,在执行了一定次数后,现在它表示分段错误。我有一个函数,我在后面的函数范围的末尾使用new分配了内存我已经包含了delete [] p。我应该在main函数中包含delete吗?

#include<iostream>
using namespace std;

void input(){
    int n,d, i= 0, count;
    cout<< "number of variables: "<<" ";
    cin>>n;
    cout<<"enter number of minterms: "<<" ";
    cin>>count;
    int x =  pow(2, n);

    int *p = new int[count] ; //dynamic allocation

    for(i = 0; i<count; i++)
    {   
        cout<< "enter the minterms in decimal: ";
        cin>>d;    
        p[i] = d;
    }

    for( i =0; i< count; i++){
        cout<<p[i]<<" ";
    }

    delete [] p; //(Do I need  to write delete over here or in the main                           
    //func, Right now I've used it here(i.e,the user defined function.)
    cout<<"successfully deallocated";
}

//Main function:
int main(){

    int *p = NULL; //Is this required ?


    input();
    //delete[] p; (Do I need to mention delete over here?)
    return 0;
}

number of variables:  4
enter number of minterms:  8
enter the minterms in decimal: 1
enter the minterms in decimal: 2
enter the minterms in decimal: 3
enter the minterms in decimal: 4
enter the minterms in decimal: 5
enter the minterms in decimal: 6
enter the minterms in decimal: 7
enter the minterms in decimal: 8
1 2 3 4 5 6 7 8 successfully deallocated00000000119614428832765154679997521907-10100852163265911961440643276540008000800080004000-1005...<a lot of numbers>...07370419492536907748609097595Segmentation fault (core dumped)
c++ memory-management dynamic segmentation-fault delete-operator
3个回答
0
投票

我已经测试了你的代码,对我来说它运行没有问题。

如果在main()中分配空间,那么通常也应该在main()中释放它。


0
投票

您在输入中创建的指针p与您在main中创建的指针无关。因此,当您返回main时,无法访问您在输入中创建的数组。

如果这是你想要做的,你“不能”删除输入中的p,将其返回到main,在main中使用它,然后在main中删除它。然而,拆分新的和删除这样的并不是最好的编码实践。

如果你不想在main中使用数组,你应该在main函数中删除对p的任何引用,不需要将它设置为null,当然也不能删除它。


0
投票

这段代码在clang,g ++和vc ++下运行良好。示例:https://rextester.com/PBN39654

这让我觉得构建代码时环境有问题,或者在main成功返回后触发核心转储。你是如何构建这个演示的?

但是你可以改进一些事情。例如:

  • 不要手动使用DMA ...尝试支持std::vector
  • 始终初始化变量。未初始化的非静态本地(作用域)变量(例如n,dcount)将收到垃圾值。
  • x不在任何地方使用。去掉它。
  • int *p = NULL有几个缺陷,其中一个是NULLNULL0的宏观。如果您确实想要创建一个指向任何内容的指针,请使用nullptr。其次,int *p与函数中的指针无关,所以它没用。去掉它。

这是更新示例的演示:https://rextester.com/BUTV13117

© www.soinside.com 2019 - 2024. All rights reserved.