Segfault when deleting pointer

后端 未结 5 1535
南笙
南笙 2021-01-03 12:32

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 pro

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 13:05

    You should only ever delete memory that has been allocated with new. Automatic variables declared on the stack do not need to be deleted. As a rule, always match your memory allocation and deallocation types:

    • Memory allocated with new should be deallocated with delete.
    • Memory allocated with new [] should be deallocated with delete [].
    • Memory allocated with malloc() should be deallocated with free().

    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.

提交回复
热议问题