Memory Allocation
You can notice memory leak in a gradual increasing memory utilization.
In C++
Use the new
keyword.
Do not forget!
Do NOT forget to free the memory at the end of the program by using the
delete
keyword, else you will have memory leak.
new
vs.malloc
?In C++, you can still use
malloc
. The difference is thatnew
allocates memory AND initializes.
Null pointers are represented as nullptr
.
Consider the following:
- I just assumed that calling the
delete
keyword automatically sets it to anullptr
. - Rather, the pointer becomes a dangling pointer, meaning it still holds the memory address of the deallocated memory, but the memory itself is no longer valid for your program to use.
= delete
keyword
=
delete
keywordThe =
delete
keyword is used to disable a certain function. Often used to disallow copying. Source
Disallow copying:
In C
We use malloc
and free
from stdlib.h
library to allocate and deallocate memory from the Heap.
How does malloc
and free
work under the hood?
They are not constant time operations. They are actually really complicated.
https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work
From ChatGPT:
- malloc: Allocates a specified amount of memory by checking a list of free blocks. If a suitable block is found, it’s removed from the list and returned. If not, more memory is requested from the OS. It maintains metadata for memory management.
- free: Deallocates memory allocated by
malloc
by adding the block back to the free list. It may merge adjacent free blocks (coalescing) to reduce Fragmentation. The function does not always return memory to the OS immediately.