C++ for Quantitative Finance: Hands-On - Memory Management

 

Memory Management

Dynamic Memory Allocation

Malloc Function

New Operator

New [] Operator

2D Arrays

 

  • Memory Areas: We'll differentiate between Stack, Data Section, and Heap memory.
  • Allocation Types: We'll compare stack-based allocation with dynamic memory allocation.
  • C Memory Management: We'll dive into malloc, calloc, realloc, and free.
  • C++ Memory Management: We'll learn about new and delete.
  • Common Pitfalls: We'll identify and understand memory leaks and dangling pointers.
  •  

    In the practice you will have to avoid the use of some of these. But understanding of raw dynamic memory allocation using new/delete and C-style malloc/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

     

     

     

     

    FeatureStack AllocationDynamic (Heap) Allocation
    AllocationAutomaticManual / RAII
    LifetimeCurrent scopeUntil released
    SpeedVery fastSlower
    SizeLimitedMuch larger
    ManagementAutomaticProgrammer or smart pointer
    RiskStack overflowMemory leaks, dangling pointers

     

    When to use dynamic memory:

  • Size is determined at runtime.
  • Object must survive beyond the current scope.
  • Managing large or complex structures (trees, graphs, caches).
  •  

    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

     

    // Prefer
    std::vector<int> data(1000);

    // Avoid
    int* data = new int[1000];
    delete[] data;

    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(...).

    #include <cstdlib>
    #include <iostream>

    int main() {
        int *a = (int*)std::malloc(5 * sizeof(int));

        for (int i = 0; i < 5; ++i) {
            a[i] = i + 1;
        }

        int *a = (int*)std::calloc(5 * sizeof(int));

        int *temp = (int*)std::realloc(a, 10 * sizeof(int));

        if (temp != nullptr) {

            for (int i = 5, i < 10, ++i) {
                a[i] = i + 1;
            }
        }

        for (i = 0; i < 10; ++i) {
            std::cout << a[i] << " ";
        }

        std::cout << "\n";

        // free release memory
        std::free(a);
        std::free(b);

        //safe
        a = nullptr;
        b = nullptr;

        return 0;
    }

     

     

     

      

     

     

     

    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).

     


     

    /* ////////////////////////////////////////////// */
    // Ilustrative examples of:
    // memory lead
    // pointer dangling

    void lead_ilustration() {
        int ptr = new int(43);

        // forgot to dellect ptr
        // delete ptr;
    }

    void dangling_pointer_ilustration() {
        int ptr = new int(43);
        delete ptr;
        ptr = 10;
    }
     
    /* ////////////////////////////////////////////// */
    // best practice to avoid both problems

    #include <memory>

    auto ptr = std::make_unique<int>(42);

    // Memory is automatically released.
    // No memory leak.
    // No dangling pointer.
     

     

     Casting

    Casting converts a value from one type to another. 

    Use static_cast for normal conversions, dynamic_cast for safe inheritance casting, and avoid reinterpret_cast unless truly necessary.

     

     

    Entradas populares

    Lo mas consultado

    Entradas populares