ece150: add pointer problems

This commit is contained in:
eggy 2022-10-31 13:13:35 -04:00
parent 4d150574f9
commit 8b77e109f6

View File

@ -203,10 +203,40 @@ If deleting arrays, `delete[]` should be used instead.
### Wild pointers ### 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 ### 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 ### 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 ## Pointers
!!! definition !!! definition