Search code examples
c++stlvectordynamic-memory-allocation

c++ std::vector Orphan Range error


A program dealing with graphs(from graph theory) representation and transformation.The adjacency list and matrix are implemented like dynamic arrays of vectors(don't ask why not vector of vector) for the following function program exits with memory error and compiler pointing to the orphan vector definition.

int vertex,edges;
vector<int> *adjacencyList,*adjacencyMatrix;

void listToAdMatrix(int vertexNumber, vector<int> *List, vector<int> *Matrix){
 int in=0,cont=0;
 for(int i=0;i<vertexNumber;i++){
  in=i;
  for(auto j=List[in].begin();j!=List[in].end();j++){
   for(int k=0;k<vertexNumber;++k){
    if(k==*j) Matrix[cont].push_back(1); 
    else Matrix[cont].push_back(0);
   }
   cont++;
  }
 }
}

//function call
//vertex(number) and ajacencyList are initialized

adjacencyMatrix=new vector<int>[vertex];
listToAdMatrix(vertex,adjacencyList,adjacencyMatrix);

The "source of error" in STL where compiler points:

http://i51.tinypic.com/2dt0t9e.jpg


The error message:

Unhandled exception at 0x001a543b in graph.exe: 0xC0000005: Access violation reading location 0xfdfdfe01.


the fillList function used to fill the adjacency list :

void fillList(int vertexNumber, vector<int> *List){
    int input=0;
    for (int i=0;i<vertexNumber;i++){   
        int in=i;
        cout<<"Introduce adjacent vertexes for the vertex -"<<i+1<<"-:"<<endl;
        for(int j=0;j<vertexNumber;j++){
            std::cout<<i+1<<"-";
            std::cin>>input;
            if(input==0) break;
            List[i].push_back(input-1);
        }
    }
}

Any clue is welcome.



Solution

  • Problem Solved :

    Once again i've read outside of an array.The error was in the cont variable which i used to address the vectors in the Matrix(dynamic array), incrementing it while it got outside the array.Problem is solved by inserting a while statement.Thank you all for the answers.

    int vertex,edges;
    vector<int> *adjacencyList,*adjacencyMatrix;
    
    void listToAdMatrix(int vertexNumber, vector<int> *List, vector<int> *Matrix){
     int in=0,cont=0;
     for(int i=0;i<vertexNumber;i++){
      in=i;
      for(auto j=List[in].begin();j!=List[in].end();j++){
       while(cont!=vertexNumber){
         for(int k=0;k<vertexNumber;++k){
           if(k==*j) Matrix[cont].push_back(1); 
           else Matrix[cont].push_back(0);
         }
         cont++;
       }
      }
     }
    }
    
    //function call
    //vertex(number) and ajacencyList are initialized
    
    adjacencyMatrix=new vector<int>[vertex];
    listToAdMatrix(vertex,adjacencyList,adjacencyMatrix);