C++ Memory Occupation

  1. Sections of memory

    You can create variables/objects on two sections of memory stack or heap.

    • Stack creation
      Stack creation is much faster than heap creation, but if variable gets out of scope (once the block within which it is declared is exited) the memory gets freed and we can't access that memory. You can create variable on stack just using type and name.

      int a = 5; // stack variable

      You can also create object on stack

      class Entity{
      private:
          const char* m_name;
      public:
          Entity() : m_name("Unknown")
          {
          }
      };
       
      Entity e1; // stack object

      You can also create array on stack;

      int numbers[5]; // stack array
    • Heap creation
      Heap variables arent destroyed if they get out of scope, instead you must destroy them manualy or they get destroyed if program ends. Heap allocation is much slower than on the stack. To create heap variables/objects you need to use new keyword and pointers.

      int* a = new int; // heap allocated variable

      Object on the heap

      class Entity{
      private:
          const char* m_name;
      public:
          Entity() : m_name("Unknown")
          {
          }
      };
      Entity* e1 = new Entity(); // heap allocated object

      Array on the heap

      int* numbers = new int[5]; // heap allocated array

      To free heap memory you use delete keyword and then variable name

       int* a = new int;
       
       delete a;

      If you free memory for heap array you will use [] after delete keyword

      int* numbers = new int[5];
       
      delete[] numbers;