覆盖矢量<vector <>&gt;和分段错误

时间:2016-11-30 11:05:08

标签: c++ vector segmentation-fault adjacency-list

我正在尝试编写一个程序,在该程序中,我在循环的每一步创建一个邻接列表,表示随时间变化的图形。 这是代码:

#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);
       }
    }
 }
}

然而,在某些时候我得到了分段错误。事实上,我认为这可能不是覆盖矢量的正确方法。我还补充说,我想在每一步更改N_nodes。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:-2)

对于细分错误部分,您可以使用Valgrind尝试找出代码中的哪些操作正在无效位置进行写入。

此外,您可以使用信号捕获Segmantation故障,但捕获分段错误不是一个好习惯