我正在尝试创建一个数组,填充后将导致创建一个更大的新数组,将旧数组的值复制到前一个数组中,并将继续将值添加到旧数组离开的新数组中离开。当我添加到第一个数组时,我的代码工作正常,但是一旦我在填充原始数组后尝试调用 append,我最终会收到一个奇怪的错误:
*** glibc detected *** demo: double free or corruption (fasttop): 0x0000000000602010 ***
不知道发生了什么事!我不太确定为什么。
#include <iostream>
using namespace std;
class ArrayList {
public:
int* array;
public:
int capacity = 0;
int size = 16;
ArrayList() {
array = new int(size);
}
void append(int data) {
if (size == capacity) {
int* tmp = new int(size+16);
for (int i = 0; i != size; i++) {
tmp[i] = array[i];
delete [] array;
}
array = tmp;
} else {
array[capacity] = data;
capacity++;
// std::cout << *(array+15) << std::endl;
}