user1771164
user1771164

Reputation: 3

Heap Corruption when trying to free two dimensional array

Why does the heap get corrupted when executing this code? I didn't work with memory allocation that much, yet.

#include <stdlib.h>

void main()
{
    char **field, x, _fieldsX, _fieldsY;

    _fieldsX = 8;
    _fieldsY = 16;

    // Allocation
    field = malloc(sizeof(char*) * _fieldsX);
    for (x = 0; x < _fieldsY; x++)
        field[x] = malloc(sizeof(char) * _fieldsY);

    // Freeing
    for (x = 0; x < _fieldsY; x++)
        free(field[x]);
    free(field);
}

Upvotes: 0

Views: 352

Answers (2)

Darren
Darren

Reputation: 792

The code allocates fields to be _fieldsX in length, but sets _fieldsY elements. This is not correct.

Upvotes: 0

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43548

You get out of the bounds of the allocated area in the first loop:

field = malloc(sizeof(char*) * _fieldsX);

for (x = 0; x < _fieldsY; x++)
    field[x] = malloc(sizeof(char) * _fieldsY);

Notice that you are allocating _fieldsX items, but the loop goes _fieldsY times over that area.

Upvotes: 1

Related Questions