使用循环重新调整数组大小

时间:2014-03-17 00:40:30

标签: c++ arrays memory-management memory-leaks allocation

我正在尝试在调用grow()时重新调整数组的大小,如果我当前的数组很小则继续向前面或后面添加值。

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_;
}

array_是类.h文件中私有变量的一部分

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)

根据Valgrind的说法,我在忘记内存方面遇到了一些问题: 读取大小4无效 地址0x59ff044在大小为4 alloc&#39; d

的块之后为0字节

2 个答案:

答案 0 :(得分:0)

问题是你永远不会释放旧记忆。

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

array_ = temp;

应该是:

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

delete[] array_;
array_ = temp;

您也可以使用memcopy代替for-loop。

答案 1 :(得分:0)

如果你分配内存你必须释放它,否则它会泄漏。

int *temp = new int[capacity_];

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

delete [] array_;  // this leaks if you don't free it.

array_ = temp;
++allocs_;