Lessons Learned from C&C++ Pointer to Pointer Program
Original Code
1 | /* |
Incorrect delete of Stack-Allocated Pointer-to-Pointer
Error:
I wrote:
1 | delete ptrToPtr; |
But ptrToPtr was not allocated with new, so deleting it causes undefined behaviour and a crash.
Lesson:
ptrToPtris a pointer to a pointer. Specifically, it points toptr.ptris dynamically allocated withnew int;, so it’s safe todelete ptr;.BUT
ptrToPtris not dynamically allocated. It just points to a local variableptr, which lives on the stack.Calling
delete ptrToPtr;tries to free stack memory, which causes undefined behaviour, hence the runtime error.Only call
deleteon pointers that were allocated usingnew.In this case,
ptrToPtrwas just pointing to a local (stack-allocated) variableptr, so:delete ptrToPtr;is invalid, becauseptrToPtrpoints to stack memorydelete ptr;is correct, becauseptrpoints to heap memory.
Correct Way:
1 | delete ptr; |
How to Declare a Pointer to a Pointer on the Heap
To declare and allocate a pointer-to-pointer on the heap, we need to use new operatior twice—once for the outer pointer(ptrToPtr) and once for the inner pointer(ptr). Here’s how it works:
1 |
|
ptrToPtrpoints to a pointer on the heap (new int*).*ptrToPtris a pointer to an int, which also lives on the heap (new int).This setup is entirely heap-allocated.
We must delete both: first the inner
int, then the outerint*.
Final Corrected Code
1 |
|
Key Takeaways for Future Code:
1. Stack vs Heap Memory
Stack memory is automatically managed. You must not delete it manually.
1
2
3
4
5cpp
复制编辑
int* ptr; // lives on the stack (DO NOT delete)Heap memory is manually allocated and must be freed.
1
2
3
4
5cpp
复制编辑
int* ptr = new int; // lives on the heap (MUST delete)
2. Ownership of Memory
- You should only
deletememory you explicitly allocated withnew. - Never delete something just because you have a pointer to it.
3. Correct Usage of Pointer to Pointer
- You can use a pointer-to-pointer to access and modify dynamically allocated memory indirectly.
- But you shouldn’t confuse the indirection with ownership—having
int**doesn’t mean you own that memory unless you usednewon that level.
- Title: Lessons Learned from C&C++ Pointer to Pointer Program
- Author: Ricardo Pu
- Created at : 2025-04-21 14:52:50
- Updated at : 2025-04-21 15:12:44
- Link: https://ricardopotter.github.io/RicardoBlog/2025/04/21/Lessons-Learned-from-C-CPP-Pointer-to-Pointer-Program/
- License: This work is licensed under CC BY-NC-SA 4.0.