Segmentation faults in atoi and argv using FFTW

1.7k views Asked by At

I am attempting just an example run of a FFT using the fftw3 library. I re-compiled my code with debugging flags and did a backtrace which gave me:

    gdb) backtrace
    #0  0x0000003e3a037172 in ____strtoll_l_internal () from /lib64/libc.so.6
    #1  0x0000003e3a033f20 in atoi () from /lib64/libc.so.6
    #2  0x0000000000400887 in main (argc=1, argv=0x7fffffffc998) at fftw_ex.c:7

but going back into my code, I don't see what's wrong with it:

    #include <stdio.h>
    #include <stdlib.h>
    #include <complex.h>
    #include "fftw3.h"
    int main(int argc, char* argv[])
    {
      printf("argc is: %d\n", argc);
      printf("argv[1] is: %d\n", *argv[1]);
      printf("argv[2] is: %d\n", *argv[2]);
      int n=atoi(argv[1]);
      int i, cutoff = atoi(argv[2]);

    // ^seg faults here according to backtrace^ //

      double *x=malloc(n*sizeof(double));
      for(i=0; i<n; ++i) x[i]=((double) rand())/((double)RAND_MAX+1.0);
      printf("x=[");
      for(i=0; i<n; ++i) printf("%15.7g ",x[i]);
      printf("];\n\n");

      double complex *in, *out;

      fftw_plan p;

      in  = (double complex*) fftw_malloc(sizeof(double complex) * n);
      out = (double complex*) fftw_malloc(sizeof(double complex) * n);

      for(i=0; i<n; ++i) in[i]=(x[i]+0.*I);

      p = fftw_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
      fftw_execute(p);
      fftw_destroy_plan(p);

      printf("y=[");
      for(i=0; i<n; ++i)
        printf("%15.7g + %15.7gi ", 1./((double) n)*creal(out[i]), 1./((double) n)*cimag(out[i]));
      printf("];\n\n");
      out[0]=0.+0.*I;
      p = fftw_plan_dft_1d(n, out, in, FFTW_BACKWARD, FFTW_ESTIMATE);
      fftw_execute(p);
      printf("z=[");
      for(i=0; i<n; ++i)
        printf("%15.7g + %15.7gi ", 1./((double) n)*creal(in[i]), 1./((double) n)*cimag(in[i]));
      printf("];\n\n");
      for(i=1; i<n/2+1; ++i)
        if (i > cutoff)
          out[i]=out[n-i]=0.+0.*I;
        printf("r=["); for(i=0; i<n; ++i)
        printf("%15.7g + %15.7gi ", 1./((double) n)*creal(out[i]), 1./((double) n)*cimag(out[i]));
      printf("];\n\n");
      fftw_execute(p);
      printf("q=["); for(i=0; i<n; ++i)
      printf("%15.7g + %15.7gi ", 1./((double) n)*creal(in[i]), 1./((double) n)*cimag(in[i]));
      printf("];\n\n");
      fftw_destroy_plan(p);
      fftw_free(in);
      fftw_free(out);
    }

EDIT: updated code - argc value is 3, so indices seem to be correct. I also printed my argv values to see where I was getting segfault, but now things started working! I'm very surprised...

1

There are 1 answers

0
Pete Becker On BEST ANSWER

Check the value of argc before you access the argv array; you can't go beyond argv[argc-1].