The following code crashes right before upon program exit. I have tested it on both MSVS 2015 and GCC. The program is just assigning a VLA on the heap (read about it here if you want) and reads a file contents character by character and storing this character in the array. The program works perfectly well. It does and prints everything correctly. However upon exiting it crashes, or it ceases to respond.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define rows 8
#define columns 8
// allocate a VLA on the heap
void allocateVLArray(int x, int y, char(**ptr)[rows][columns])
{
*ptr = malloc(sizeof(char[rows][columns]));
assert(*ptr != NULL);
}
int main()
{
char (*grid)[rows][columns];
allocateVLArray(rows, columns, &grid);
if (grid) {
FILE *inputFile = fopen("test_fgetc.txt", "r");
if (inputFile) {
int x = 0, y = 0, length = 0;
char ch;
while((ch = (char)fgetc(inputFile)) != EOF) {
// CR and LF characters are captured together (if necessary) and counted as one char using '\n'
if (ch == '\n') {
x++; y = 0;
}
else {
*grid[x][y] = ch;
y++;
}
length++;
}
for (x = 0; x < rows; x++) {
for (y = 0; y < columns; y++) {
printf("%c", *grid[x][y]);
}
printf("\n");
}
printf("\nlength = %d\n", length);
}
}
free(grid);
return 0;
}
I've also noticed my constant memory usage has increased significantly, which means memory leaks. So It is probably a heap problem. Why is this happening and how can i fix it?