Segfault when deleting pointer
Solution 1
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:
- Memory allocated with
new
should be deallocated withdelete
. - Memory allocated with
new []
should be deallocated withdelete []
. - Memory allocated with
malloc()
should be deallocated withfree()
.
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.
Solution 2
You can't use delete
on anything you didn't get with new
. Trying to do so will cause undefined behaviour. Your program crashed, but anything could have happened.
Solution 3
Calling delete on a pointer, deallocates the dynamically allocated memory that the pointer points to.
In the first program, pointer points to a statically allocated memory location.The variable number is an 'automatic' variable, which means that its memory is automatically managed.
On the other hand in the second program, pointer is pointing to a memory location allocated in the heap segment, which needs to be manually deallocated by calling delete.
You might find this link useful.
rnorris
Updated on June 04, 2022Comments
-
rnorris almost 2 years
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.