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

How to clear dynamically allocated memory using delete [] operator? (Unable to clear with regular delete syntax)

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

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

#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)

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

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

你在 input 中创建的指针 p 独立于你在 main 中创建的指针。所以当你回到 main 时,你不能访问你在 input 中创建的数组。

如果那是你想做的,你"can"不要删除输入中的p,return它到main,在main中使用它,然后在main中删除它。然而,像这样拆分新的和删除的并不是最佳编码实践。

如果你不想在main中使用数组,你应该在main函数中删除所有对p的引用,不需要设置为null,更不能删除它。

此代码在 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