在函数内部使用 fftw3 会产生分段错误

Using fftw3 inside a function produce segmentation fault

测试以下代码我得到了正确的答案:

#include <fftw3.h>
void dump_vector(float *a, int size)
{
    int i;
    for (i = 0; i < size; i++) {
        printf("%f\t", a[i]);
    }
    printf("\n");
}

int main()
{
    float a[] = {1, 2, 3, 4};
    dump_vector(a, 4);
    fftw_plan plan = fftw_plan_r2r_1d(2 * 2, a, a, FFTW_REDFT10, FFTW_ESTIMATE);
    fftw_execute(plan);
    dump_vector(a, 4);
}

结果:

./main
1.000000    2.000000    3.000000    4.000000    
3.992188    4.501953    -334878449985782808576.000000   3.886292

但我想为 dct 做一个天真的包装所以:

#include <fftw3.h>
void dump_vector(float *a, int size)
{
    int i;
    for (i = 0; i < size; i++) {
        printf("%f\t", a[i]);
    }
    printf("\n");
}

void dct(float * array, int xsize, int ysize)
{
    fftw_plan plan = fftw_plan_r2r_1d(xsize * ysize, array, array, FFTW_REDFT10, FFTW_ESTIMATE);
    fftw_execute(plan);
}


int main()
{
    float a[] = {1, 2, 3, 4};
    dump_vector(a, 4);
    dct(a, 2, 2);
    dump_vector(a, 4);
}

结果:

./main
1.000000    2.000000    3.000000    4.000000    
3.992188    4.501953    -334878449985782808576.000000   3.886292    
[1]    10880 segmentation fault  ./main

有什么我遗漏的吗?

我需要这样做,因为我想生成一个 .so 文件以便在另一个应用程序中使用它。

问题比预期的要简单得多:fftw_plan_r2r_1ddouble 的数组执行 DCTs/DSTs。

原样,数组 float a[] 太小:4 float 存储在 4x4=16 字节中,而 fftw_plan_r2r_1d 需要 4 double (32 字节) .因此,fftw_plan_r2r_1d 将尝试读取实际数组的末尾。这会触发未定义的行为,例如分段错误或错误结果。

两种解决方案:

  • float a[] 更改为 double a[],将 dump_vector(float *a,... 更改为 dump_vector(double *a,...
  • 使用 fftwf_plan_r2r_1d()float 的数组构建 fftwf_plan。请参阅 http://www.fftw.org/doc/Precision.html :必须通过将 -lfftw3f 添加到编译器命令来链接库 libfftw3f.a