简体   繁体   中英

Segmentation fault when trying to fill a vector as instance variable

I want to make a filled matrix as an instance variable in my.hpp file but end up with seg fault.

I have a graphe class. In my.cpp file, i filled an adjacency matrix as follows

void Graphe::shortRoute( void ){
    std::vector<vector<int>> matrix(_adjacences.size(), vector<int>(_adjacences.size()));
    std::vector<vector<int>> shortPath(_adjacences.size(), vector<int>(_adjacences.size()));
    
    for (unsigned i = 0; i < _adjacences.size(); i++) {
                for (auto j : *_adjacences[i]) {
                        matrix[i][j->sommetArrive] = j->longueur;
                }
        } 
... more and more code to get a filled shortPath matrix.

I implemented Floyd algorithm and everything works perfectly here and I printed the matrix to check it, it's all good.

the resulted matrices matrix and shortPath I wanted to make as instance variables

I tried as follows THIS CAUSES SEG FAULT WHY?

for ( unsigned i = 0; i < _adjacences.size(); i++)
    for (unsigned j = 0; j < _adjacences.size(); j++){
         shortPath[i][j] = SP[i][j];
         matrix[i][j] = M[i][j];
    }

and in my.hpp file I declared SP and M as follows:

class Graphe
{
private:
    vector< vector< Arc * > * > _adjacences;
    std::vector<vector<int>> M;
    std::vector<vector<int>> SP;
....

as soon as I launch the program, i get seg fault from that new addition

Arc is as follows:

class Arc
{
public:
    int sommetArrive;
    int longueur;
    string nom;

    Arc( int a_sommetArrive, int a_longueur, string a_nom );
    virtual ~Arc( void );

    friend ostream & operator <<( ostream &, Arc const & );
};

Not what you are asking about but this code

for ( unsigned i = 0; i < _adjacences.size(); i++) 
    for (unsigned j = 0; j < _adjacences.size(); j++) { 
        shortPath[i][j] = SP[i][j]; 
        matrix[i][j] = M[i][j]; 
    }

can be simplified to this

 shortPath = SP; 
 matrix = M; 

You don't have to write loops to copy vectors, the whole vector can be copied in a single assignment.

I have a suspicion this might even cure your problem. If so then the original problem was probably that the shortPath and matrix vectors are zero size, so the loop code is assigning to vector elements that don't exist. When you copy a vector using a single assignment the size of the vector you are copying to changes to match the size of the vector you are copying from.

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