Search code examples
c++memoryheap-memorynew-operatorfstream

Heap Corruption Error - Allocating memory


I dont know what is going on - but somehow my code is corrupting heap

....
unsigned char *buf[2] = {0};
buf[0] = new unsigned char(sizeof(BITMAPFILEHEADER));
buf[1] = new unsigned char(sizeof(BITMAPINFOHEADER));

if(! buf[0] || ! buf[1])
{
    std::cout << "running outta memory " << std::endl;
    return false;
}

file.read((char*)buf[0], sizeof(BITMAPFILEHEADER));
file.read((char*)buf[1], sizeof(BITMAPINFOHEADER));

m_bmpHeader = (BITMAPFILEHEADER*) buf[0];
m_bmpInfo = (BITMAPINFOHEADER*) buf[1];

if(m_bmpHeader->b_filetype[0] != 'B' || m_bmpHeader->b_filetype[1] != 'M' ||
    m_bmpInfo-> compression != 0 || m_bmpInfo-> bits_per_pixel != 24)
{
    std::cout << "Not a valid BMP file..Supporting 24 bit images only" ;
    return false;
}

m_data = new unsigned char[m_bmpInfo->imagesize];
if(! m_data)
{
    std::cout << "running outta memory " << std::endl;
    return false;
}

heap is getting corrupted at the point m_data = new unsigned char[m_bmpInfo->imagesize];

If I debug the code - it stops in fstream; inside templated _Fgetc kinda saying EOF has been hit

Thank you for your help in advance


Solution

  • new unsigned char(sizeof(BITMAPFILEHEADER));
    

    This does not allocate an array! It allocates a single unsigned char.

    Write:

    new unsigned char[sizeof(BITMAPFILEHEADER)];
    

    You get that right later on in your code, so presumably this is just a typo.