简体   繁体   English

C ++:St9bad_alloc对于小输入失败

[英]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. 但是它显示了St9bad_alloc错误,而我的列表只有3个大小。

Also, adjnew[2].back() is assigned to "0" without being initialized, whereas it should have some garbage value. 同样,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

' '

All suggestions are welcomed! 欢迎所有建议!

The

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

at begin is plain undefined behavior on an empty container. 开始时,在空容器上的行为是普通的未定义行为。

valgrind gives valgrind给

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. 提示:您可以使用container.at()代替operator []进行范围检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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