我的random_walk代码导致“分段错误(核心已转储)”

时间:2019-12-07 08:53:26

标签: c linux

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <stdbool.h>
#define PI 3.1415926535898

// the usage
void usage(char *program) {
  fprintf(stderr, "\nProgram Usage:\n%s\n", program);
  fprintf(stderr,
          "     [ -n  1000000 ]    number of steps per run, default 10000\n");
  fprintf(stderr,
          "     [ -o output.dat ]  the output file, default: output.dat\n");
  fprintf(stderr, "     [ -h ]             display this information\n");
  fprintf(stderr, "\n");
  exit(1);
}

// function to get system arguments from command line
void getMyArgs(int argc, char **argv, int *nstep, char *filename) {
  char ch;
  while ((ch = getopt(argc, argv, "n:o:h")) != -1) {
    switch (ch) {
    case 'n':
      *nstep = atoi(optarg);
      break;
    case 'o':
      *filename = *optarg;//as if there is the error.
      break;
    case 'h':
      usage(argv[0]);
    case '?':
      usage(argv[0]);
    }
  }
}

// function to get the distance from the start point
double dist(double *site) { return sqrt(site[0] * site[0] + site[1] * site[1]); }

// function to output the data
void output(FILE *fp, int istep, double *site) {
  fprintf(fp, "%10d %10.2f %10.2f %10.2f\n", istep, site[0], site[1],
          dist(site));
}

// function to get the step
void getStep(double *step) {
  /* get the degree */
  double deg = rand() / (double)RAND_MAX* 2 * PI;
  step[0] = sin(deg);
  step[1] = cos(deg);
}

// function run the step
void runStep(double *site, double *step,double s) {
  site[0] += s*step[0];
  site[1] += s*step[1];
}

//probability function
bool proba(double p){
    if(rand()/RAND_MAX<p)
      return true;
    else
      return false;
}

// the main program
int main(int argc, char *argv[]) {

  // for parameters
  int nstep = 1000;    
  char *filename = "output.dat"; 
  getMyArgs(argc, argv, &nstep, filename);

  srand((unsigned)time(0)); 

  // the initial state
  double site[] = {0.0, 0.0};
  FILE *fp = fopen(filename, "w");
  output(fp, 0, site);

  // walking ....
  int i;
  for (i = 1; i <= nstep; ++i) {
    double step[2],s=1;
    if (proba(0.8)==1)
    {
      if(proba(0.5)==1)
      {
        s=0.5; 
      }  
      getStep(step);
      runStep(site, step,s);
    }
    output(fp, i, site);
  }
  fclose(fp);

}

这是我的random_walk代码。运行data.dat时,该函数应输出./a.out -n 1000 -o data.dat。但这总是会导致 Segmentation fault (core dumped)

当我运行output.dat时,它可以输出具有1000个静态变量的./a.out -n 1000

我猜这应该是由filename = *optarg引起的,但我无法正确理解。


我已经按照@kaylum的说法更改了代码。但是GCC告诉我:

random_walk.c: In function ‘getMyArgs’:
random_walk.c:30:17: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
       *filename = *optarg;

然后我运行./a.out -n 10000 -o data.dat,结果为:

Segmentation fault (core dumped)

0 个答案:

没有答案