cmallocvalgrindbmpmemory-corruption

Unknown reason for malloc "corrupted top size" error


I've been working on a small project and while just after finishing a function that indirectly calls the one below, I started getting the malloc: corrupted top size error. I have used Valgrind to narrow down the problem to the fread in said function, but I cannot find any mistake in how it is written. Am I just blind, or should I start looking elsewhere?

The offending function:

bmpHead_t* readBMPHeader(FILE* inputFile){
    checkBMPFile(inputFile);
    bmpHead_t* newHeader = malloc(sizeof(bmpHead_t));
    int headerSize = sizeof(bmpHead_t) / 2;
    uint16_t* wordBuff = malloc(headerSize);
    fseek(inputFile, 0, SEEK_SET);
    fread(wordBuff, sizeof(uint16_t), headerSize, inputFile);
    newHeader->signature[0] = (uint8_t)((wordBuff[0] & 0xFF00) >> 8);
    newHeader->signature[1] = (uint8_t)(wordBuff[0] & 0xFF);
    uint32_t tmp = ((uint32_t)wordBuff[2] << 16) | wordBuff[1];
    newHeader->fileSize = tmp;
    newHeader->reserved1 = wordBuff[3];
    newHeader->reserved2 = wordBuff[4];
    tmp = ((uint32_t)wordBuff[6] << 16) | wordBuff[5];
    newHeader->offToPixels = tmp;
    return newHeader;
}

For context, the header I'm reading is the Windows BITMAPFILEHEADER.


Solution

  • As stated by Jeremy Friesner in a comment underneath my post, I was allocating an improper amount of memory.