Search code examples
c++mfcheap-corruption

Heap corruption in MFC program


I am having a problem with a heap corruption issue in a program. In the program I am reading a block of data and performing FFT and IFFT on it. I am doing it for 2 images, master and slave. The EXACT same code works fine for the master but shows a heap corruption for the slave file when I try to delete the slave buffer.

fcomplex is defined as:

typedef struct {float real, imag;}fcomplex;

A snippet of relevant parts of the code is attached: Full code: http://sharetext.org/7xXe

The error does not occur if I do not call the fft and ifft functions for the slave image. (Everything works fine for the master though)

To debug the error I installed Application verifier but I was not able to decode the log file. Its here: http://sharetext.org/Y2ji (XML file copy pasted)

The error visual studio give is: Heap corruption Detected: after normal block (#194456) at 0x062C0040

CCoarseFun::fcomplex * slave_bfr;
CCoarseFun::fcomplex * slave_col;


slave_bfr = Pcoarse.init_1Dcmplx(SIZE*s_cols); 
slave_col = Pcoarse.init_1Dcmplx(SIZE);

Pcoarse.cfft1d_(&SIZE,slave_col,&FFTdir); // This function causes a problem
Pcoarse.complex_mult_col(filter, slave_col, SIZE, slave_col)
Pcoarse.cfft1d_(&SIZE,slave_col,&FFTdir); // As does this one

// delete memory related to slave
delete [] slave_bfr;    // Heap corruption here
delete [] slave_col;

What is baffleing me is that the code is pretty simple and it works 100% for only the master files. Why is it crashing for the slave?

Can some one guide me to a solution or maybe a tutorial on how to use the Application verifier as well?

Thanks, Shaunak

EDIT: Using Win7 x64 - VS2010

EDIT 2: Definition for init_1Dcmplx

CCoarseFun::fcomplex* CCoarseFun::init_1Dcmplx(int n)
{
  fcomplex *a;
  a=new fcomplex[n];
  for(int i=0;i<n;i++)
  {
    a[i].real=float(0.0);
    a[i].imag=float(0.0);
  }
  return a;
}

EDIT3: COde for cfft1D_ : http://sharetext.org/hzIg

EDIT4: Code for mem.delfloat()

void CMemAlloc::del_float(float *a)
{
  if (a!=NULL)
  {
    delete[] a;
    a=NULL;
  }
  else
  {
    return;
  }
}

Solution

  • The mem_float() function is not correct. It looks like it is setting the pointer to NULL after the delete, but it is only working on a copy of the pointer, so the caller's copy is still pointing to deleted memory block.

    You can just do

    delete [] cf;
    cf = NULL;
    

    You have a couple of lines that look like this:

    four1(cf-1,nn,isign);
    

    I think this is accessing memory before the beginning of the array.

    Beyond this, the indexing inside four1() is insanely complicated - you will have to step through it with the debugger to check the edge cases.