C++ 如何使用delete[]操作符清除动态分配的内存?(无法使用常规删除语法清除)
我使用int*p=newint[size]分配了一个动态内存强> 现在,当我尝试使用delete[]p删除它时;我在执行代码时遇到分段错误(核心转储)。 最初,我能够动态地输入数组元素,它工作正常。但是,在执行了一定次数之后,现在它说 分段错误。我有一个函数,在该函数的作用域末尾,我使用new分配了内存,我包括delete[]p。我是否应该在主函数中包含deleteC++ 如何使用delete[]操作符清除动态分配的内存?(无法使用常规删除语法清除),c++,memory-management,dynamic,segmentation-fault,delete-operator,C++,Memory Management,Dynamic,Segmentation Fault,Delete Operator,我使用int*p=newint[size]分配了一个动态内存 现在,当我尝试使用delete[]p删除它时;我在执行代码时遇到分段错误(核心转储)。 最初,我能够动态地输入数组元素,它工作正常。但是,在执行了一定次数之后,现在它说 分段错误。我有一个函数,在该函数的作用域末尾,我使用new分配了内存,我包括delete[]p。我是否应该在主函数中包含delete #include<iostream> using namespace std; void input(){ in
#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;
}
#包括
使用名称空间std;
无效输入(){
int n,d,i=0,计数;
cout我已经测试了你的代码,对我来说它运行没有问题
如果在main()中分配空间,则通常也应在main()中取消分配空间。在输入中创建的指针p独立于在main中创建的指针。因此,当返回main时,无法访问在输入中创建的数组
如果这就是您想要做的,您“不能”删除输入中的p,将其返回到main,在main中使用它,然后在main中删除它。但是像这样拆分new和delete并不是最佳编码实践
如果不想在main中使用数组,则应在main函数中删除对p的任何引用,无需将其设置为null,当然也不能将其删除。此代码在clang、g++和vc++下运行良好。
例如:
这让我觉得要么是你构建代码的环境出了问题,要么是在main成功返回后触发了核心转储。你是如何构建这个演示的
然而,有些事情你可以改进。
例如:
- 不要手动使用DMA…尝试使用
std::vector
- 始终初始化变量。未初始化的非静态局部(作用域)变量,如
n、d
和count
将接收垃圾值
x
未在任何位置使用。请将其删除
int*p=NULL
有几个缺陷,其中一个是NULL
NULL
是指向0
的宏。如果要创建一个不指向任何内容的指针,请使用nullptr
。其次,int*p
与函数中的指针无关,因此它是无用的。请删除它
这是一个更新的示例的演示:
1。如果你可以,避免问题中的大量输出文本。2。你使用C++作为C。使用智能指针,使用Null pTR代替Null,代码中没有任何东西可以产生该输出。
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)