Memory Allocation
You can notice memory leak in a gradual increasing memory utilization.
In C++
Use the new keyword.
Coord* p = new Coord {};
p->x = 10;
p->y = 20; // play around
delete p;Do not forget!
Do NOT forget to free the memory at the end of the program by using the
deletekeyword, else you will have memory leak.
newvs.malloc?In C++, you can still use
malloc. The difference is thatnewallocates memory AND initializes.
Null pointers are represented as nullptr.
Consider the following:
Node* node;
delete node->left;
cout << node->left; // does NOT print nullptr (i.e. 0)
// you NEED to do this
node->left = nullptr;
cout << node->left; // works as intended, prints nullptr (i.e. 0)- I just assumed that calling the
deletekeyword 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
=
deletekeywordThe =
deletekeyword is used to disable a certain function. Often used to disallow copying. Source
Disallow copying:
class X {
X& operator=(const X&) = delete; // Disallow copying
X(const X&) = delete;
};In C
We use malloc and free from stdlib.h library to allocate and deallocate memory from the Heap.
void *malloc(size_t size);
// Allocates block of memory of size number of bytes but doesn't initialize.
// Returns a pointer to it.
// If insufficient memory or size==0, returns NULL, the null pointer.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
mallocby 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.