写入大小为4的数组无效

时间:2014-01-23 13:40:23

标签: c++ valgrind

我正在用C ++制作一个Vector类,我遇到了一些问题。

==23391== Invalid write of size 4
==23391==    at 0x401CAB: IntVector::IntVector(int, int) (IntVector.cpp:35)
==23391==    by 0x401009: main (main.cpp:36)
==23391==  Address 0x4c25218 is 0 bytes after a block of size 200 alloc'd
==23391==    at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==23391==    by 0x401C7F: IntVector::IntVector(int, int) (IntVector.cpp:32)
==23391==    by 0x401009: main (main.cpp:36)



IntVector::IntVector(int size, int value){
capacity = INITIAL_CAPACITY;
while(size >= capacity)
{
    capacity = capacity*2;
}
if(size < 0)
{
    count = 0;
    array = new int[capacity];
}
else
{
    count = size;
    array = new int[capacity];  // line 32
    for(int i = 0; i < count; i++)
        {
            array[i] = value; //line 36
        }
}

为什么我可以通过数组读取或写入?在主要我声明v1(5,0)initial capacity = 50,循环只到4,所以它不应该读取或写入超过50!

1 个答案:

答案 0 :(得分:1)

不应该这个

  

array = new int [50]; //第32行

是吗?

array = new int[capacity];