简体   繁体   中英

C++: St9bad_alloc failure for small Input

I built a program for converting a multigraph into undirected graph with multiple edges and self loops removed using adjacency-list as Graph representation. `

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

`

But it shows St9bad_alloc error whereas my list has size of just 3.

Also, adjnew[2].back() is assigned to "0" without being initialized, whereas it should have some garbage value.

'

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

'

All suggestions are welcomed!

The

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

at begin is plain undefined behavior on an empty container.

valgrind gives

Conditional jump or move depends on uninitialised value(s)

for this line:

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

Again an undefined behavior on an empty container.

Hint: You could use container.at() instead of operator [] to have a range check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM