C++:小输入的St9bad_alloc故障

C++: St9bad_alloc failure for small Input

本文关键字:alloc 故障 St9bad 输入 C++      更新时间:2023-10-16

我构建了一个程序,用于将多图转换为无向图,其中使用邻接列表作为图表示移除了多条边和自循环。`

 #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;

在一个空容器上的begin是未定义的行为。

valgrind给出

Conditional jump or move depends on uninitialised value(s)

对于这条线路:

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

在空容器上再次出现未定义的行为。

提示:您可以使用container.at()而不是运算符[]来进行范围检查。