C++ for Quantitative Finance: Hands-On - Memory Management
Memory Management
Dynamic Memory Allocation
Malloc Function
New Operator
New [] Operator
2D Arrays
malloc, calloc, realloc, and free.new and delete.
In the practice you will have to avoid the use of some of these. But understanding of raw dynamic memory allocation usingnew/deleteand C-stylemalloc/free. This foundational knowledge is essential for understanding how memory works at a lower level, even when using higher-level abstractions like smart pointers.
In modern C++, avoid raw new and delete. Prefer stack allocation and RAII with smart pointers (std::unique_ptr, std::shared_ptr) for safe and automatic memory management.
Memory Areas
- Stack
- Head
- data section
| Feature | Stack Allocation | Dynamic (Heap) Allocation |
|---|---|---|
| Allocation | Automatic | Manual / RAII |
| Lifetime | Current scope | Until released |
| Speed | Very fast | Slower |
| Size | Limited | Much larger |
| Management | Automatic | Programmer or smart pointer |
| Risk | Stack overflow | Memory leaks, dangling pointers |
When to use dynamic memory:
Best practice in moderm c++
Prefer stack allocation by default. Use dynamic allocation only when lifetime or size requirements make it necessary. When dynamic memory is needed, prefer RAII and smart pointers over raw new and delete.
Functions for allocatin memory
Fron Heap
There is not reason to use malloc in c++.
Malloc allocate raw memory on the heap and not initialized it, while calloc initializes it to 0. Realloc allocates larger chunk of memory for an existing allocation. And free releases the memory allocated through these functions.
malloc() returns void*. In C++, you usually need to cast it, e.g. int* p = (int*)malloc(...).
Be carefull to avoid:
Memory leak: Memory allocated but never released.
Dangling pointer: is a pointer that refers to memory that is no longer valid (freed memory).
Casting
Usestatic_castfor normal conversions,dynamic_castfor safe inheritance casting, and avoidreinterpret_castunless truly necessary.
