Search code examples
c++dynamic-memory-allocation

C++: Reallocating memory without cstdlib


Couldn't find exact answer to the question:

Is freeing memory and allocating again the only way to reallocate memory without using cstdlib? If not so, then what are the possible solutions?

Thanks in advance.


Solution

  • If you are implementing your own vector class, then you do need to properly copy the contents of the vector, not use realloc, since you don't know what the object itself is doing when it is being copied (or in C++11 for relevant cases, moved). Imagine for example that you have an object that does something like this:

    class B;
    
    class A
    {
      private:
        B* bp;
      public:
        A(B *p) : bp(p)
        {
        }
    };
    
    
    class B
    {
      public:
       A a;
       B() : A(this)
       {
          ... 
       }
     };
    
    MyVector<B> v; 
    

    If you copy the object to a different address, without calling the constructor, the bp pointer in A will point to some "random" place. That would be a pretty nasty bug to try to find.

    [And yes, there is a bunch of stuff missing in the above classes - it is not meant as a complete class declaration, etc, etc]