From 4d150574f9cee08016d801c536fa6ecc4a95d780 Mon Sep 17 00:00:00 2001 From: eggy Date: Thu, 27 Oct 2022 14:46:04 -0400 Subject: [PATCH] ece150: add allocation --- docs/ce1/ece150.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/ce1/ece150.md b/docs/ce1/ece150.md index 6e88f08..9eecc4d 100644 --- a/docs/ce1/ece150.md +++ b/docs/ce1/ece150.md @@ -174,6 +174,39 @@ If there is not a null terminator, attempting to access a string continues to go Compared to static memory allocation, which is done by the compiler, dynamic memory is managed by the developer, and is stored between the call stack and data segment in the **heap**. +The `new` operator attempts to allocate its type operand, optionally initialising the variable and returning its memory address. + +```cpp +char *c{new char{'i'}}; +``` + +If the operating system cannot allocate that much memory, `std::bad_alloc` is raised, but passing in `nothrow` can return a `nullptr` instead if allocation fails. + +```cpp +char *c{new(nothrow) char{`i`}}; + +if (c == nullptr) { +} +``` + +The `delete` operator tells the OS that the memory address passed is no longer needed. Generally, it is a good idea to set the deleted pointer afterward to a null pointer. + +```cpp +delete c; +c = nullptr; +``` + +If deleting arrays, `delete[]` should be used instead. + +!!! warning + Statically allocated memory **cannot be deallocated** manually as it is done so by the compiler, so differentiating the two is generally a good idea. + +### Wild pointers + +### Dangling pointers + +### Memory leaks + ## Pointers !!! definition