堆损坏错误 - 分配内存

时间:2015-01-12 22:15:35

标签: c++ memory heap new-operator fstream

我不知道发生了什么 - 但不知怎的,我的代码破坏了堆

....
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;
}

堆在m_data = new unsigned char[m_bmpInfo->imagesize];

点被破坏

如果我调试代码 - 它会在fstream中停止;内部模板_Fgetc有点说EOF已被击中

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

new unsigned char(sizeof(BITMAPFILEHEADER));

这不分配数组!它分配了一个unsigned char

写:

new unsigned char[sizeof(BITMAPFILEHEADER)];

您稍后会在代码中获得该权限,因此可能这只是一个错字。