c++ - 大小为 4 的数组递增大小的无效读取

标签 c++ arrays valgrind

我在运行 Valgrind 时遇到 4 个错误,试图递增我用于模板堆栈的数组(最初大小为 10),当我尝试向数组添加第 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++;         
    }

我不确定 new 运算符和 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)

谢谢。

最佳答案

正如 Dave S 所提到的,if (_count <= _size)条件导致您的堆损坏。将条件更改为 if (_count < _size)将导致您期望的行为。

实际上,您将从 0 迭代到 10,在触发溢出之前总共推送 11 次。

关于c++ - 大小为 4 的数组递增大小的无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083748/

相关文章:

c++ - 根据模板是指针/引用还是无来选择函数

c - 了解 Valgrind 输出

android - Qt Android : Why is a QtApp-debug. apk 为发布版本创建?

c++ - 如何在可变类模板中获取类型的索引?

DLL 中的 Python (c++) Visual Studio

c++ - 为什么 valgrind 显示泄漏,即使包含动态分配对象的 vector 已被释放?

c++ - 使用 C++11 std::condition_variable 的 Gtest 意味着 valgrind 错误

javascript - 一般使用javascript map函数是什么意思?

javascript - 如何从 AngularJS 数组中删除搜索到的条目

c - 添加数组元素的总和给出了错误的输出?