Reputation: 3
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
Reputation: 792
The code allocates fields to be _fieldsX in length, but sets _fieldsY elements. This is not correct.
Upvotes: 0
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