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);
}
You get out of the bounds of the allocated area in the first loop:
Notice that you are allocating
_fieldsXitems, but the loop goes_fieldsYtimes over that area.