當我嘗試洗掉宣告為的陣列指標時
short *width = NULL;
width = new short[lenght];
delete[] width;
程式在洗掉部分停止并回傳一個亂數。
這是我的所有程式
int main(){
short **junction = NULL, *width = NULL, length = 0;
ifstream input;
input.open("sample_input.txt");
if(!input)
cout << "No such a file named \"sample_input.txt\"" << endl;
else if(input >> length){
junction = new short*[length];
width = new short[length];
string str;
for(int i = 0; i - 1 < length && getline(input, str); i ){
istringstream ss(str);
width[i - 1] = (str.size() 1) / 2; //numbers can be two char, so in this case, here we allocate more than necessary memory
junction[i - 1] = new short[width[i - 1]];
for(int j = 0; j < width[i - 1]; j ){
if(ss.eof()){
junction[i - 1][j] = -1; // -1 is the key value of emtpy spaces
continue;
}
ss >> junction[i - 1][j];
}
}
}
input.close();
/*
for(int i = 0; i < length; i )
delete[] junction[i];
delete[] junction;
delete[] width;
*/
return 0;
}
評論部分有問題,我單獨嘗試了那些洗掉陳述句,只是因為部分正在運行,但不像我預期的那樣,這是我的示例輸入:
uj5u.com熱心網友回復:
您的代碼實際上應該沒問題。請向我們展示整個程式。
florian@florian-desktop:~$ cat -n test2.cpp
1 #include <iostream>
2 int main()
3 {
4 const int length = 4;
5 short *width = NULL;
6 width = new short[length];
7 delete[] width;
8 }
florian@florian-desktop:~$ valgrind ./a.out
==22630== Memcheck, a memory error detector
==22630== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==22630== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==22630== Command: ./a.out
==22630==
==22630==
==22630== HEAP SUMMARY:
==22630== in use at exit: 0 bytes in 0 blocks
==22630== total heap usage: 2 allocs, 2 frees, 72,712 bytes allocated
==22630==
==22630== All heap blocks were freed -- no leaks are possible
==22630==
==22630== For lists of detected and suppressed errors, rerun with: -s
==22630== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Valgrind 顯示所有保留的記憶體都已正確釋放。
- 更新:
我更正了您的完整代碼:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main() {
short **junction = NULL, *width = NULL, length = 12;
ifstream input;
input.open("sample_input.txt");
if(!input)
cout << "No such a file named \"sample_input.txt\"" << endl;
else if(input >> length){
junction = new short*[length];
width = new short[length];
string str;
for(int i = 0; i < length && getline(input, str); i ){
istringstream ss(str);
width[i] = (str.size() 1) / 2; //numbers can be two char, so in this case, here we allocate more than necessary memory
junction[i] = new short[width[i]];
for(int j = 0; j < width[i]; j ){
if(ss.eof()){
junction[i][j] = -1; // -1 is the key value of emtpy spaces
continue;
}
ss >> junction[i][j];
}
}
}
input.close();
for(int i = 0; i < length; i )
delete[] junction[i];
delete[] junction;
delete[] width;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/469332.html
上一篇:帶有函式指標的結構體
下一篇:這個Cfor回圈的終止條件是什么