Quaker
Quaker

Reputation: 1553

Heap error while trying to deallocate memory

I wrote a program to allocate a matrix of PIXELs, each PIXEL is a struct that holds:

typedef struct Pixel {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char gray;
} PIXEL;

Each matrix is being allocated using the following function:

PIXEL** createImageMatrix(FILE *fp, int height, int width)
{
    PIXEL **res;
    int i, j;

    res = (PIXEL**)malloc(sizeof(PIXEL*)*height);
    checkalloc(res);

    printf("-->createImageMatrix()\n");
    for (i = 0; i < height; i++)
    {
        res[i] = (PIXEL*)calloc(width, sizeof(PIXEL));
        checkalloc(res[i]);
        printf("matrix[%d]: %p \n", i, res[i]);
    }
    printf("<--createImageMatrix()\n");
    return res;
}

and deallocated using the following function:

void freeImageMatrix(PIXEL **matrix, int height)
{
    int i;

    printf("-->freeImageMatrix()\n");
    for (i = 0; i < height; i++)
    {
        printf("matrix[%d]: %p \n", i, matrix[i]);
        free(matrix[i]);
    }
    printf("<--freeImageMatrix()\n");
    free(matrix);
}

The call for freeImageMatrix() is the following:

freeImageMatrix(matrix, height);

For debugging matters I print the addresses when they're allocated, get values and when I try to free them. This is the output on command line:

-->createImageMatrix()
matrix[0]: 0x00881AA8
matrix[1]: 0x00881AE8
matrix[2]: 0x00881B28
matrix[3]: 0x00881B68
matrix[4]: 0x00881BA8
<--createImageMatrix()
-->freeImageMatrix()
matrix[0]: 0x00881AA8
Press any key to continue . . .

And the error window that pops up says the following:

HEAP CORRUPTION DETECTED: after Normal block (#79) at 0x0061AA8.
CRT detected that the application wrote to memory after end of heap buffer.

The addresses which I allocate and try to deallocate match, so why in god's name is this happening to me?

Additions

checkalloc():

void checkalloc (void* memory)
{
    if (memory==NULL)
    {
        printf("\nMemory allocation failed!\n");
        free(memory);
        exit (1);
    }

And this is how the values in the matrix gets their values:

    for (j = 0; j < width; j++)
    {
        fscanf(fp, "%u", &(res[i][j]).red);
        fscanf(fp, "%u", &(res[i][j]).green);
        fscanf(fp, "%u", &(res[i][j]).blue);
        res[i][j].gray = (res[i][j].red + res[i][j].green + res[i][j].blue) / 3;
    }

Upvotes: 0

Views: 229

Answers (1)

Neil Hampton
Neil Hampton

Reputation: 1883

Somewhere else in your program there is a bug which is corrupting the heap which just happens to manifest itself when you try to free something off the heap.

I would look at the code prior to the freeImageMatrix call.

Upvotes: 1

Related Questions