我已经实现了我自己的简单向量,所有函数似乎都很好,除了在alloc_new()
上,当它尝试创建新内存并复制内容并删除旧内存分配时。
我的程序总是挂起,之后就再也没有执行过。
class myvector{
private:
int vsize, maxsize;
int* arr;
void alloc_new();
public:
myvector();
myvector(int);
myvector(const myvector&);
~myvector();
void push_back(int);
int size();
int operator[](int);
int at(int);
void display();
};
myvector::myvector(){
maxsize = 20;
vsize = 0;
arr = new int[maxsize];
}
void myvector::alloc_new(){
// Allocate new space, double of current size
maxsize = maxsize*2;
int* arr_new = new int[maxsize];
//copy the elements from the base location to new location
for(int i=0; i < vsize ; i++)
arr_new[i] = arr[i];
delete[] arr; // MY PROGRAM ALWAYS HANGS HERE
arr = arr_new;
}
void myvector::push_back(int val){
if((vsize+1) > maxsize)
alloc_new();
arr[++vsize] = val;
}
int main(){
myvector vect;
for(int i=0;i<25;i++){
vect.push_back(rand()%100+1);
}
getch();
}
答案 0 :(得分:2)
问题是你的“我们达到最大尺寸”是错误的。您正在比较vsize + 1 > maxsize
。这意味着您在arr[++vsize]
时写信至vsize + 1 == maxsize
。这会写一个元素PAST你的分配[换句话说,索引20是0..19是有效索引],因此出错了。
修复如下代码:
void myvector::push_back(int val){
if((vsize+1) >= maxsize)
alloc_new();
arr[++vsize] = val;
}
使用valgrind会告诉你:
$ valgrind ./a.out
==20918== Memcheck, a memory error detector
==20918== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==20918== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==20918== Command: ./a.out
==20918==
==20918== Invalid write of size 4
==20918== at 0x4009E9: myvector::push_back(int) (in /home/MatsP/src/junk/a.out)
==20918== by 0x400AA1: main (in /home/MatsP/src/junk/a.out)
==20918== Address 0x5a20090 is 0 bytes after a block of size 80 alloc'd
==20918== at 0x4C2A77C: operator new[](unsigned long) (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==20918== by 0x4008B4: myvector::myvector() (in /home/MatsP/src/junk/a.out)
==20918== by 0x400A57: main (in /home/MatsP/src/junk/a.out)
==20918==
==20918==
==20918== HEAP SUMMARY:
==20918== in use at exit: 0 bytes in 0 blocks
==20918== total heap usage: 2 allocs, 2 frees, 240 bytes allocated
==20918==
==20918== All heap blocks were freed -- no leaks are possible
==20918==
==20918== For counts of detected and suppressed errors, rerun with: -v
==20918== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)