ece150: add allocation
This commit is contained in:
parent
62a8acb596
commit
4d150574f9
@ -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**.
|
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
|
## Pointers
|
||||||
|
|
||||||
!!! definition
|
!!! definition
|
||||||
|
Loading…
Reference in New Issue
Block a user