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

时间:2016-06-04 15:33:55

标签: c segmentation-fault fftw

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

template <class T, class V> bool find(T const &t, V const &v) {
    return std::find(t.begin(), t.end(), v) != t.end();
}

template <class V> bool find(std::set<V> const &t, V const &v) {
    return t.find(v) != t.end();
}

template <class V> bool find(std::unordered_set<V> const &t, V const &v) {
    return t.find(v) != t.end();
}

template <class K, class V> bool find(std::map<K, V> const &t, K const &v) {
    return t.find(v) != t.end();
}

template <class K, class V> bool find(std::unordered_map<K, V> const &t, K const &v) {
    return t.find(v) != t.end();
}

结果:

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

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

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

结果:

#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 文件,以便在另一个应用程序中使用它。

1 个答案:

答案 0 :(得分:1)

问题比预期的要简单得多:fftw_plan_r2r_1d double 的数组上执行DCT / DST。

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

两种解决方案:

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