我已經使用動態分配的數組爲C++編寫了一個雙精度序列的類。運行程序時,它成功完成,但valgrind正在查找錯誤。當我調用resize函數時,我收到大小爲8的無效讀取。無效的讀取大小爲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;
}
}
調整大小正被稱爲附加:
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==
我試圖運行的valgrind與--leak- check = full和--read-var-info = yes,並且無法確定我爲什麼會收到此錯誤。調整大小的第45行是:new_vals [i] = data [i];
謝謝!
不要將'used'設置爲'new_capacity'。在這之前檢查'used'是否大於'new_capacity'。另外,這裏不應該有'std :: vector'嗎? –
是的std :: vector將是一個完美的工具,但這是一個家庭作業,我必須重新發明輪子。 我更新了上面的代碼,它現在檢查new_capacity是否在設置之前用於new_capacity。我仍然在同一個地方得到同樣的錯誤。 –
然後我會說可能會有一些代碼在其他方法中修改'used'出現問題。 (另外,在將'data'設置爲'new_vals'之前,您似乎忘記了'delete [] data'; o) –