Search code examples
c++pointersnew-operatordynamic-memory-allocation

Why does operator "new" require a pointer to work?


I cannot wrap my head around why the memory in the stack allocated through new can be accessed only through pointers, while the memory in the heap (statically allocated) can be accessed normally.

Does it have something to do with the fact that pretty much all memory in the heap has some sort of order and the one in the stack is somewhat random? (If what I just said is true at all.)

Dynamic memory just seems so vague and mystical to me, so anyone who could help me understand it better will be hugely appreciated.


Solution

  • Why does operator “new” require a pointer to work?

    Becouse it allocates block of memory (size is specified by caller) on heap and returns address of the beginning of that allocated block.

    Why are we using it

    • We're using it if we want that memory temporary, so we can easily delete[] it.

    • You can easily change the size of the allocated memory (resize).

      char arr[20]; // You need more space? Not possible to change size
      
      // While
      
      char * arr = new char[20];
      
      delete[] arr;
      
      arr = new char[50];
      

    Disadvantage

    • Allocating object with new is much more expensive.

    • Its slower.

    • Memory leak's

    • Memory fragmentation

    • Has to be free'd delete[]

    Summary

    Stack (automatic storage) is easier to use, faster & foolproof. But sometimes we have to use heap and we should be careful as much as possible.