I trying to build fft function in c++. I realized there are errors in the process so I wanted to print each step on it's own. When I try to do cout to everything that is not a string it trigger a breakpoint and error: "A heap has been corrupted " In the main it sometimes and sometimes not Any help, or suggestions would be much appreciated.
Edit : Code after fix
complex<double>* fft(complex<double>* signal, int len)
{
if (len == 1) return signal;
else
{
const complex<double> J(0, 1);
const double PI = 3.14159265358979323846;
const double THRESHOLD = 1e-10;
complex<double> w(1, 0);
complex<double>* x_d1 = new complex<double>[len / 2];
complex<double>* x_d2 = new complex<double>[len / 2];
for (int i = 0; i < len/2; i++)
{
x_d1[i] = signal[2*i];
x_d2[i] = signal[2*i + 1];
}
complex<double>* y_1 = fft(x_d1, len / 2);
complex<double>* y_2 = fft(x_d2, len / 2);
complex<double>* dft = mergePointers(y_1, y_2, len / 2);
delete[] x_d1, x_d2, y_1, y_2;
for (int k = 0; k < len/2; k++)
{
complex<double> p = dft[k];
complex<double> w_k = exp(J * ((-2*PI*k) / len));
complex<double> q = w_k * dft[k + (len / 2)];
dft[k] = p + q;
dft[k + len / 2] = p - q;
if (abs(dft[k].real()) < THRESHOLD) dft[k] = complex<double>(0, dft[k].imag());
if (abs(dft[k].imag()) < THRESHOLD) dft[k] = complex<double>(dft[k].real(), 0);
if (abs(dft[k + (len / 2)].real()) < THRESHOLD) dft[k + (len / 2)] = complex<double>(0, dft[k + (len / 2)].imag());
if (abs(dft[k + (len / 2)].imag()) < THRESHOLD) dft[k + (len / 2)] = complex<double>(dft[k + (len / 2)].real(), 0);
}
return dft;
}
}
You allocated dynamically arrays with len / 2
elements. But in for loops like this
for ( int i = 0; i <= len/2; i++ )
you are trying to access len / 2 + 1
elements that results in undefined behavior. The valid range of indices is [0, len / 2 )
.
You have to write
for ( int i = 0; i < len/2; i++ )