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.
You should only ever
deletememory that has been allocated withnew. Automatic variables declared on the stack do not need to bedeleted. As a rule, always match your memory allocation and deallocation types:newshould be deallocated withdelete.new []should be deallocated withdelete [].malloc()should be deallocated withfree().The segfault is because the
deleteoperator 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.