Memory Management

Fundamentals on Computing for Robotics, Graphics and Computer Vision

Darío Suárez - Adolfo Muñoz

Memory Management

  • Memory stores programs; i.e., instructions and data
  • The Operating System and the C++ runtime manages memory

Quiz: What is a variable?

A pair of a name with its semantics and a corresponding location for storage, normally memory

Quiz: What is a pointer?

A variable that stores a memory address

Quiz: Assuming a 64-bit address space, what are the sizes of all variables in the figure?

Parts of a Program in Memory

  • According to ELF, programs are divided into segments (memory), sections (linker)

Text and Operating System parts

  • Operating System: The operating system restricts some memory area for itself
  • Text: Memory segment storing the code of our program; e.g., main function

Data, Heap, and Stack and variable scopes

  • Data: Area storing global variables with lifetime equal to the program
  • Heap: Area storing variables dynamically allocated, unknown lifetime and not function limited
  • Stack: Area storing variables created within the scope of a function

Example of variables and their section mapping

Heap and Stack example

source: https://courses.grainger.illinois.edu/cs225/fa2022/resources/stack-heap/

Quiz: Pointers' storage

Can the heap, stack and data sections store pointers?

Quiz: What is the output of this code?

C++ parameters default pass

In C++, pass-by-copy is the default policy

Quiz: What is the output of this code?

Pointers to the rescue

Pointers can be dangerous

nullptr, the pointer literal

  • nullptr represents the null pointer constant
  • Its type is std::nullptr_t can be converted to any pointer type
  • Never use NULL or 0 for pointers

NULL bad use example

source: https://learn.microsoft.com/es-es/cpp/cpp/nullptr?view=msvc-170

References

  • An alias to an already-existing object or function
  • Access to references are the same to the object they point to

Reference example

Pointers and Arrays

Arrays

  • Definition: contiguously allocated nonempty sequence of objects with a particular element type. Size cannot change
  • Example: int array[3]={0, 1, 2};
  • Normally, they will be allocated in the stack
  • Please prefer std::array container over arrays

Dynamic Memory Allocation

  • Dynamic memory is stored in the heap section. Enlarges and reduces at run time
  • Allocation:
    int * ptr_int = new int;
    int * array_int = new int[4];
  • Deallocation:
    delete ptr_int;
    delete [] array_int;
  • Manually managing dynamic memory is error-prone. Please be very disciplined
  • Pointer Arithmetic

    • C++ allows arithmetic operations on pointers
    • a[i] == *(a + i * sizeof(a[0]))

    Quiz: what is the final value of these pointers

      Please assume all pointers point to address 16
      uint8_t *ptr = 16; ptr+=2;
      int *ptr = 16; ptr=nullptr;
      int *ptr = 16; ptr+=3;