From 8b77e109f6915c19c7ae875d5d80b55b75c67c5a Mon Sep 17 00:00:00 2001 From: eggy Date: Mon, 31 Oct 2022 13:13:35 -0400 Subject: [PATCH] ece150: add pointer problems --- docs/ce1/ece150.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 9eecc4d..3c2a4ce 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -203,10 +203,40 @@ If deleting arrays, `delete[]` should be used instead. ### Wild pointers +A wild pointer is any uninitialised pointer. Its behaviour is undefined. Accessing unallocated memory results in a **segmentation fault**, causing the OS to terminate the program. + +!!! warning + Occasionally, the OS does not prevent program access to deallocated memory for some time, which may allow the program to reuse garbage pointers, allowing the pointer to work. This causes inconsistent crashing. + +To avoid wild pointers, pointers should always be initialised and set to `nullptr` if not needed even if they would go out of scope. + ### Dangling pointers +A dangling pointer is one that has been deallocated, which has the same issues as a wild pointer, especially if two pointers have the same address. + +!!! example + `p_2` is dangling. + + ```cpp + int* p_1{}; + int* p_2{p_1}; + + delete p_1; + ``` + +To avoid dangling pointers, pointers should be immediately set to `nullptr` after deleting them. Deleting a `nullptr` is **guaranteed to be safe**. + ### Memory leaks +A memory leak occurs when a pointer is not freed, such as via an early return or setting a pointer to another pointer. This causes memory usage to grow until the program is terminated. + +!!! example + The `new int[20]` has leaked and is no longer accessible to the program but remains allocated memory. + ```cpp + int* p{new int[20]}; + p = new int[10]; + ``` + ## Pointers !!! definition