我已经使用 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)
最佳答案
此代码在 clang、g++ 和 vc++ 下运行良好。 示例:https://rextester.com/PBN39654
这让我认为您构建代码的环境有问题,或者在 main 成功返回后其他原因触发了核心转储。你是如何构建这个演示的?
但是有些事情您可以改进。 例如:
- 不要手动使用 DMA...尽量使用
std::vector
- 总是初始化你的变量。未初始化的非静态局部(作用域)变量,例如您的
n,d
和count
将收到垃圾值。 x
没有在任何地方使用。将其删除。int *p = NULL
有几个缺陷,其中之一是NULL
。NULL
是0
的宏。如果您确实想创建一个不指向任何内容的指针,请使用nullptr
。其次,int *p
与函数中的指针无关,所以没有用。去掉它。
这是更新示例的演示:https://rextester.com/BUTV13117
关于c++ - 如何使用 delete [] 运算符清除动态分配的内存? (无法使用常规删除语法清除),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55440140/