简体   繁体   中英

Overwriting vector<vector<> > and segmentation fault

I'm trying to write a program in which at each step of a loop I create an adjacency list representing a graph that changes in time. Here's the code:

#include <iostream>                                              
#include <fstream>         
#include <string>           
#include <sstream>         
#include <vector>         
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>                                           
#include <boost/random/mersenne_twister.hpp>                  
#include <boost/random/variate_generator.hpp>                 
#include <boost/random/uniform_int.hpp>                        
#include <boost/random/uniform_real.hpp>
#include <boost/random/exponential_distribution.hpp>

using namespace std;
using std::vector;

 typedef boost::mt19937_64 ENG; // use Mersenne Twister 19937 as PRNG engine
 typedef boost::uniform_int<> DIST_INT; // define uniform distribution of integers
 typedef boost::uniform_real<> DIST_REAL; // define uniform distribution of reals on [0,1)
 typedef boost::exponential_distribution<> DIST_EXP; // define exponential distribution
 typedef boost::variate_generator<ENG,DIST_INT> VARIATE_INT;
 typedef boost::variate_generator<ENG,DIST_REAL> VARIATE_REAL;
 typedef boost::variate_generator<ENG,DIST_EXP> VARIATE_EXP;

int main()
{  
 const unsigned int random_seed = time(NULL);
 // ======= initialize BOOST machines
 ENG eng(random_seed);
 DIST_INT dist_int;
 DIST_REAL dist_rand(0,1);
 DIST_EXP dist_exp;
 VARIATE_INT randint(eng,dist_int); //random integer. use as: randint(N)
 VARIATE_REAL rand(eng,dist_rand); //random float on [0,1[. use as: rand()
 VARIATE_EXP randexp(eng,dist_exp); //random exponentially distributed float.
 int N = 500, Tmax=200000, v, w;
 float p = 0.2, s;
 vector<vector<int> > contact_list;
 for(int i = 0; i < 200000; i++)
 {
  contact_list.resize(N, vector<int>());
  v = 1;
  w = -1;
  while(v < N)
    {
      s = rand();
      w += 1 + int(log(1-s)/log(1-p));
      while((w >= v) && (v < N))
       {
        w = w - v;
        v += 1;
       }
      if (v < N)
       {
        contact_list[v].push_back(w);
        contact_list[w].push_back(v);
       }
    }
 }
}

However at some point I get segmentation fault. In fact I think this may not be the correct way to overwrite a vector. I also add that I would like to change N_nodes at each step. Any help is appreciated!

For the segmentation fault part you can use Valgrind to try and find out what operation in your code is writing at an invalid location.

Also you can catch Segmantation fault, with the use of signal, but it's not a good practice to catch a segmentation fault

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