大小为8的读取无效
Invalid read of size 8
我已经用一个动态分配的数组为c++中的一个双精度序列编写了一个类。。当运行程序时,它成功地完成了,但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 to new_capacity,因此如果它小于new_capasity,就会导致问题。
if (used > capacity)
resize(capacity*2); //here current index=capacity i.e maxm size allocated to new_vals
data[current_index] = entry; //current_index > capacity, this is out of reach memory for new vals and data(since data=new_vals), so you are getting invalid read.
相关文章:
- 在 valgrind c++ 上读取大小 8 无效
- Valgrind 大小为 8 且地址 0x5b7e520 的读取无效,在大小为 16 的块内为 0 字节 free'd
- 在 c++ 中使用 getter 作为unordered_map会创建大小为 8 的无效读取
- 对唯一 ptr 无效读取的引用向量
- 瓦尔格林德:构造函数中大小为 1 的无效读取
- 将文本文件读取为 const char* 有时有效,有时无效
- 瓦尔格林德在文件*上的读取无效
- (SDL 渲染问题)C++ 引发异常:读取访问冲突.这是无效的
- 无效操作数以二进制读取结构的阵列
- 获取无效或损坏的文件LNK1107:尝试链接 OpenSceneGraph 教程.dll时无法0x378读取
- 如何修复"在大小为 64 的块内读取大小为 8 - 40 字节的无效 free'd"
- Valgrind 抱怨通过指向结构的指针访问结构成员时读取无效
- VALGRIND:大小为8的读取无效
- C++:写入/读取无效/越界数组索引
- 大小为8的读取无效
- 大小8的读取无效,大小8的写入无效(Valgrind)
- Valgrind调试日志:大小为8的读取无效
- 分段故障-大小为8的读取无效
- C++ valgrid 错误:大小为 8、地址 0x8 的读取无效,未堆叠、恶意或(最近)释放?
- 将char*转换为std::string的大小为1的读取无效