【发布时间】:2014-03-17 00:40:29
【问题描述】:
如果我当前的数组太小而无法继续在前面或后面添加值,我会在调用 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 的块后的 0 个字节
【问题讨论】:
-
capacity_ = (capacity_) ? capacity_ * 2 : 1的意义何在?另外,使用std::vector可能吗?它至少会修复您的实现中存在的内存泄漏(因为您永远不会删除旧数组)。 -
@sircodesalot 如果
capacity_不为零,则将其加倍,否则将其设置为 1 -
看起来赋值基本上是实现一个自己的向量,因此实现了一个动态数组(以及为什么这个类被称为
Vector) -
另外,你在哪里释放旧内存?
-
我有另一个名为 clear 的函数,它在调用时清除分配的 array_,析构函数也释放 array_。 Aruisdante,你的假设是正确的,任务是用几个链表操作制作一个向量。这就是为什么不允许使用 std::vector 并且不允许使用 memcopy 或 realloc 的原因。
标签: c++ arrays memory-management memory-leaks allocation