我在运行Valgrind尝试递增用于模板堆栈的数组(初始大小为10)时遇到4个错误,当我尝试向数组中添加第11个元素时(恰好是当我将valgrind赋给我4个错误)必须在推送过程中增加尺寸):
class stack {
private:
int _size = 10;
T *_data;
int _top;
int _count = 0;
public:
// costructor used
stack(int s) {
this->_size = s;
_data = new T[_size];
this->_top = -1;
}
....
void push(T v) {
if (_count <= _size) {
this->_top++;
this->_data[_top] = v;
this->_count++;
}else{
//HEAP ERRORS HERE ++++++++
_size++;
T *temp = new T[_size];
for(int i = 0; i < _top; i++) {
temp[i] = _data[i];
}
delete [] _data;
_data=temp;
_data[_top] = v;
this->_top++;
this->_count++;
}
我不确定在else语句后是否有新运算符和delete [],我认为我在那里遇到了问题,但是我想不出另一种方法来解决它。
在main.cpp中,我仅压入模板堆栈中的11个元素:
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);
s.push(8);
s.push(9);
s.push(10);
s.push(11);
这是valgrind的输出
==4178== Invalid write of size 4
==4178== at 0x10921E: stack<int>::push(int) (stack.h:85)
==4178== by 0x108ED2: main (main.cpp:32)
==4178== Address 0x5b82ca8 is 0 bytes after a block of size
40 alloc'd
==4178== at 0x4C3089F: operator new[](unsigned long) (in
/usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4178== by 0x109144: stack<int>::stack() (stack.h:28)
==4178== by 0x108B8D: main (main.cpp:9)
HEAP SUMMARY:
==4178== in use at exit: 0 bytes in 0 blocks
==4178== total heap usage: 4 allocs, 4 frees, 73,808 bytes
allocated
==4178==
==4178== All heap blocks were freed -- no leaks are possible
==4178==
==4178== For counts of detected and suppressed errors, rerun with: -v
==4178== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from
0)
谢谢。
答案 0 :(得分:2)
如Dave S所述,if (_count <= _size)
条件导致堆损坏。将条件更改为if (_count < _size)
将导致您期望的行为。
照原样,您将从0迭代到10,以进行总共11次推送,然后触发溢出。
答案 1 :(得分:0)
您说过11次按下会导致错误。看来原因是<=
。当count
等于size
时,您应该扩展数组,但是您的代码会将项目推到end元素之后。
请注意,常见情况是范围边缘上的错误。为了避免这种情况,请使用单元测试。还要尝试避免开发已经完成的事情,只需使用现有的一项即可。