c++ - STL list segmentation fault on push_back -


i'm having problem when using stl's list. i'm loading digraph in format

#of_tests #of_vertexes #of_edges #vertex1 > #vertex2 #vertex3 > #vertex4 ... 

but sigsegv on first call of push_back on adjacency lists, , i'm baffled - array of lists initialized, don't call on null.

i've checked tests, , i'm within bounds (i never call method beyond allocated array).

here's code

#include <iostream> #include <list>  using namespace std;  int * deg_in; list<int> * edge; int n;  int main() {     int z;     cin >> z;      deg_in = new int[n]();     edge = new list<int>[n]();      while(z--)     {         int m;         cin >> n >> m;          while(m--)         {             int a, b;             char trash;             cin >> >> trash >> b;              /// vertexes given 1 .. n, stored 0 .. n - 1             a--;             b--;              edge[a].push_back(b);   /// code fails here             deg_in[b]++;         } /// somethig graph       delete [] deg_in;     delete [] edge; }       return 0; } 

any appreciated.

your code allocates deg_in , edge arrays before inputting n. since n declared in global scope, initialized 0 , arrays of length 0. sigsegv arises because program tries access unallocated part of memory.

in addition, delete arrays after trying process first test case , arrays not re-allocated every test case.

from context, seems deg_in , edge arrays meant per-testcase. in case, code should be:

while (z--) {     int m;     cin >> n >> m;      deg_in = new int[n]();     edge = new list<int>[n]();      // input graph      delete [] deg_in;     delete [] edge; } 

like paul r said, formatting code consistently reduce chance of simple mistakes. cheers.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -