c++ - 大小 8 的无效读取

标签 c++ memory valgrind

我已经使用动态分配的数组在 C++ 中为 double 序列编写了一个类。运行该程序时,它成功完成,但 valgrind 发现错误。调用调整大小函数时,我收到大小为 8 的无效读取。

  void sequence::resize(size_type new_capacity){
    if (new_capacity == capacity){
      return;
    }else {
      if (new_capacity < used)
          used = new_capacity;
      capacity = new_capacity;
      value_type* new_vals;
      new_vals = new value_type[capacity];
      for (int i=0;i<used;i++){
          new_vals[i] = data[i];
      }
      cout<<endl;
      delete [] data;
      data = new_vals;
    }
  }

Resize 被 attach 调用:

  void sequence::attach(const value_type& entry){
    //Behaivoir for empty sequence
    if(used == 0){
      current_index = 0;
      used++;
      if (used > capacity)
        resize(capacity*2);
      data[current_index] = entry;     
    } 
    //Behaivoir for no current_index
    else if (!is_item()){
      current_index = used;
      used++;
      if (used > capacity)
        resize(capacity*2);
      data[current_index] = entry;
    }
    //Default behaivoir
    else {
      used++;
      if (used > capacity)
        resize(capacity*2);
      for(int i = used-1; i>current_index+1;i--)
        data[i] = data[i-1];
      advance();
      data[current_index] = entry;
    }
  }

这是我在测试程序中收到的错误:

==1919== Invalid read of size 8
==1919==    at 0x400DB3: main_savitch_4::sequence::resize(unsigned long) (sequence2.cxx:44)
==1919==    by 0x401091: main_savitch_4::sequence::attach(double const&) (sequence2.cxx:95)
==1919==    by 0x403232: test5() (sequence_exam2.cxx:538)
==1919==    by 0x40414E: run_a_test(int, char const*, int (*)(), int) (sequence_exam2.cxx:744)
==1919==    by 0x404321: main (sequence_exam2.cxx:775)
==1919==  Address 0x5a1ae50 is 0 bytes after a block of size 240 alloc'd
==1919==    at 0x4C2C037: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1919==    by 0x400C33: main_savitch_4::sequence::sequence(unsigned long) (sequence2.cxx:17)
==1919==    by 0x4030AC: test5() (sequence_exam2.cxx:520)
==1919==    by 0x40414E: run_a_test(int, char const*, int (*)(), int) (sequence_exam2.cxx:744)
==1919==    by 0x404321: main (sequence_exam2.cxx:775)
==1919== 

我尝试使用 --leak-check=full 和 --read-var-info=yes 运行 valgrind,但无法确定为什么会出现此错误。 resize 的第 45 行是这样写的:new_vals[i] = data[i];

谢谢!!!

最佳答案

问题是您设置 used new_capacity 而不检查它,因此如果它小于 new_capacity 就会导致问题。

关于c++ - 大小 8 的无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555258/

相关文章:

c++ - GST_DEBUG : How to save logs in a separate file for a thread inside an application

c++ - Windows 代码页与标准 C/C++ 文件名的交互?

c++ - 在 C++ 中创建新的类型特征

java - 如何同步两个 Java 应用程序?

c - 如果我在 calloc 分配的内存之外设置一个值会怎样?

add 函数中的 C trie 内存泄漏

c++ - 如何获取字典键?

memory - 如何在 OpenCL 中使用固定内存/映射内存

mysql - MySQL InnoDB表数据同步到Memory表的方法

C 数组内存泄漏