The problem is that actually you allocated a one-dimensional array
grid = malloc(sizeof(int) * (width * height));
So dereferencing the pointer grid
like
grid[i]
you are attempting to read the uninitialized allocated memory as a value of an address that results in undefined behavior.
You need either to allocate an array of pointers to arrays that will simulate a two-dimensional array like for example
#include <string.h>
#include <stdlib.h>
//...
grid = malloc(sizeof(int *) * height);
for ( int i = 0; i < height; i++ )
{
grid[i] = malloc( sizeof( int ) * width );
}
for ( int i = 0; i < height; i++ )
{
memset( grid[i], 0, sizeof( int ) * width );
}
Or you could allocate a one dimensional array as you already did but use only one subscript operator. In this case the pointer grid
shall have the type int *
and the function will be declared like
int * alloc_grid(int width, int height);
For example
#include <string.h>
#include <stdlib.h>
//...
int *grid;
//...
grid = malloc( sizeof(int) * width * height );
memset( grid, 0, sizeof( int ) * height * width );
Or instead of calling the function memset
you could initially initialize the arrays by zero using calloc
instead of malloc
as for example
grid = malloc(sizeof(int *) * height);
for ( int i = 0; i < height; i++ )
{
grid[i] = calloc( width, sizeof( int ) );
}
or
grid = calloc( width * height, sizeof(int) );