我正在尝试使用fftw3库运行FFT的示例。我用调试标志重新编译了我的代码并进行了回溯,它给了我:
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
但回到我的代码中,我看不出它有什么问题:
#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);
}
编辑:更新的代码 - argc值为3,因此索引似乎是正确的。我还打印了我的argv值,看看我在哪里遇到段错误,但现在事情开始了!我很惊讶......
答案 0 :(得分:2)
在访问argc
数组之前检查argv
的值;你不能超越argv[argc-1]
。