Search code examples
c++arraysmemory-managementmemory-leaksallocation

Re-sizing an array with a loop


I am trying to re-size my array when calling grow() if my current array is to small to continue adding values to the front or back.

void Vector::grow(void)
{
    // Double the capacity
  capacity_ = (capacity_) ? capacity_ * 2 : 1;

  int *temp = new int[capacity_];

  for(unsigned int i = 0; i < size_; i++)
    temp[i] = array_[i];

  array_ = temp;
  ++allocs_;
}

The array_ is part of the private variables in the class .h file

private:
  int *array_;        // The dynamically allocated array
  unsigned size_;     // The number of elements in the array
  unsigned capacity_; // The allocated size of the array
  unsigned allocs_;   // Number of allocations (resizes)

I am getting some problems where I am leaking memory according to Valgrind: Invalid read of size 4 Address 0x59ff044 is 0 bytes after a block of size 4 alloc'd


Solution

  • The problem is you never free the old memory.

    for(unsigned int i = 0; i < size_; i++)
       temp[i] = array_[i];
    
    array_ = temp;
    

    should be:

    for(unsigned int i = 0; i < size_; i++){
        temp[i] = array_[i];
    }
    
    delete[] array_;
    array_ = temp;
    

    You could also likely use memcopy instead of the for-loop.