i have a struct “cell” defined as
typedef struct{
int id;
terrainType terrain;
} cell;
i then make a 2d array of cells with
cell** makeCellGrid(int sizeX, int sizeY)
{
cell** theArray;
int i;
theArray = (cell**) malloc(sizeX*sizeof(cell*));
for ( i = 0; i < sizeX; i++)
{
theArray[i] = (cell*) malloc(sizeY*sizeof(cell));
}
return theArray;
}
at first i thought this was working fine but a few seg faults later i discovered that with some values (e.g. makeCellGrid(32, 87) ) it breaks.
im fairly fresh with C pointers and memory junk and was hoping some one could point me in the right direction here.
with lower number bounds i had no issue accessing it with
map[i][j].id = x;
and so on
EDIT: forgot to add, from testing, the seg fault originate from
theArray[i] = (cell*) malloc(sizeY*sizeof(cell));
The code lacks error checking for the
malloc()system call.So if the first call to
malloc()failed the second one (in the loop) tries to assign memory toNULLwhich indeed leads to the segmentation violation your are witnessing.You might consider modifing you code like so:
Notes on my modifications:
malloc()on errorNULLis returned)unsignedtype to access memory/array indicies;size_tis meant for thisvoid *function likemalloc()ppto indicated that it’s a 2-level indirection)CellType) and variables using small letters (ppCells).sizeofoperator then some type. As the declaration of the pointer the memory is allocated to might be changed during develpment and the adjustment of the argument tomalloc()will be forgotten. To cut it short: doing as I did is less error prone.freeCellGrid()). Even better start of with coding this deallocator first, as then you have it by hand when coding the allocator’s error handling (as shown for the second call tomalloc()).