删除指针时出现段错误 [英] Segfault when deleting pointer
问题描述
运行某些C ++代码时,我一直遇到段错误.我已将问题隔离到程序中删除指针的一行.这是一个产生相同错误的简单示例:
I've been experiencing segfaults when running some C++ code. I've isolated the problem to a line in the program that deletes a pointer. Here's a simple example that produces the same error:
int main()
{
int* pointer=0;
int number = 3;
pointer = &number;
delete pointer;//This line causes a segmentation fault
pointer=0;
return 0;
}
稍作修改就会产生可以正常工作的代码:
A slight modification produces code that will work as expected:
int main()
{
int* pointer=new int(3);
delete pointer;//This line now works
pointer=0;
return 0;
}
有人可以解释为什么第一个引起段错误而第二个不引起段错误吗?我知道指针不是无效的,因为它已分配给数字变量的地址.
Can someone explain why the first causes a segfault and the second does not? I know the pointer isn't invalid, since it's been assigned to the address of the number variable.
推荐答案
您应该只使用new
分配的delete
内存.在堆栈上声明的自动变量不需要delete
d.通常,请始终匹配您的内存分配和释放类型:
You should only ever delete
memory that has been allocated with new
. Automatic variables declared on the stack do not need to be delete
d. As a rule, always match your memory allocation and deallocation types:
- 用
new
分配的内存应该用delete
释放. - 用
new []
分配的内存应该用delete []
释放. - 用
malloc()
分配的内存应该用free()
释放.
- Memory allocated with
new
should be deallocated withdelete
. - Memory allocated with
new []
should be deallocated withdelete []
. - Memory allocated with
malloc()
should be deallocated withfree()
.
segfault是因为delete
运算符将尝试将该内存放回堆中,并且该操作依赖于某些内存属性,这些属性对于不是由其产生的堆栈上的自动内存不成立堆.
The segfault is because the delete
operator will attempt to put that memory back into the heap, and that relies on certain properties of the memory that don't hold true for automatic memory on the stack that didn't originate from the heap.
这篇关于删除指针时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!