Trying to make a 2D array and am getting this error from valgrind
==226== HEAP SUMMARY:
==226== in use at exit: 0 bytes in 0 blocks
==226== total heap usage: 38 allocs, 38 frees, 9,793 bytes allocated
==226==
==226== All heap blocks were freed -- no leaks are possible
==226==
==226== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==226==
==226== 1 errors in context 1 of 2:
==226== Invalid read of size 8
==226== at 0x108BB7: freeBoard (Battleships.c:55)
==226== by 0x108B81: createBoard (Battleships.c:47)
==226== by 0x108AD6: main (Battleships.c:30)
==226== Address 0x522ff60 is 0 bytes after a block of size 32 alloc'd
==226== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==226== by 0x108B29: createBoard (Battleships.c:40)
==226== by 0x108AD6: main (Battleships.c:30)
==226==
==226==
==226== 1 errors in context 2 of 2:
==226== Invalid write of size 8
==226== at 0x108B5D: createBoard (Battleships.c:44)
==226== by 0x108AD6: main (Battleships.c:30)
==226== Address 0x522ff60 is 0 bytes after a block of size 32 alloc'd
==226== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==226== by 0x108B29: createBoard (Battleships.c:40)
==226== by 0x108AD6: main (Battleships.c:30)
==226==
==226== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
This is the code that is allocating/freeing
void createBoard(int* widthPtr, int* heightPtr) /* Creates the 2D Board Array. */
{
char** board;
int i;
board = (char**)malloc((*heightPtr) * sizeof(char*));
for (i = 0; i < *widthPtr; i++)
{
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
}
freeBoard(board, widthPtr);
}
void freeBoard(char** board, int* widthPtr)
{
int i;
for (i = 0; i < *widthPtr; i++)
{
free(board[i]);
}
free(board);
}
I'm trying to make a 2D array of a specified width/height which are integers. In each section of the array a char will be stored.
Any help would be great, thanks.