簡體   English   中英

C ++:St9bad_alloc對於小輸入失敗

[英]C++: St9bad_alloc failure for small Input

我構建了一個程序,用於將多圖轉換為無向圖,並使用鄰接列表作為圖表示形式刪除了多個邊和自循環。 `

 #include<iostream>
 #include<istream>
 #include<algorithm>
 #include<list>
 using namespace std;

int main()
{
list<int> adj[3];
list<int> auxArray[3];
list<int> adjnew[3];
cout<<adjnew[2].back()<<endl; // Gives output 0, whereas it should have some garbage
//value

for(int i = 0;i<3;i++){
int x;
while(true){ // reading a line of integers until new line is encountered , peek() 
returns the next input character without extracting it.
cin>>x;                              
adj[i].push_back(x); 
auxArray[i].push_back(x);
if(cin.peek() == '\n') break;                                             
 }        
}

//flatten the adj-list
for(int i = 0;i<3;i++){
list<int>::iterator it = adj[i].begin();
while(it != adj[i].end()){
auxArray[*it].push_back(i);
it++;
 }
}

for(int i = 0;i<3;i++){
list<int>::iterator it = auxArray[i].begin();
while(it != auxArray[i].end()){
 //cout<<*it<<" "<<adjNew[*it].back()<<endl;
if((*it != i) && ((adjnew[*it].back()) != i)){
// cout<<*it<<" -> "<<i<<endl;
 adjnew[*it].push_back(i);         
 }
 it++;
 }
}

for(int i = 0;i<3;i++){
list<int>::iterator it = adjnew[i].begin();
while(it != adjnew[i].end()){
 cout<<*it<<" ";  
 it++;       
}
cout<<endl;
}
return 0;
}

`

但是它顯示了St9bad_alloc錯誤,而我的列表只有3個大小。

同樣,adjnew [2] .back()被分配給“ 0”而不進行初始化,而應該具有一些垃圾值。

'

Input:
1 2 1
0
1 1

Output of Program(Incorrect because of 0 as back element in adjnew[2]):
1 2
0 2
1

Correct Output:
1 2
0 2
0 1

'

歡迎所有建議!

cout<<adjnew[2].back()<<endl;

開始時,在空容器上的行為是普通的未定義行為。

valgrind給

Conditional jump or move depends on uninitialised value(s)

對於這一行:

if ((*it != i) && ((adjnew[*it].back()) != i))

在空容器上再次出現未定義的行為。

提示:您可以使用container.at()代替operator []進行范圍檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM