试图制作一个2D阵列,但我从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)
这是分配/释放的代码
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);
}
我正在尝试制作一个指定宽度/高度的2D数组,这些数组是整数。在数组的每个部分中都将存储一个字符。
任何帮助都将是伟大的,谢谢。
for (i = 0; i < *widthPtr; i++)
{
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
}
应该是
for (i = 0; i < *heightPtr; i++)
{
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
}
否则,您将迭代NCOLUMNS次(您希望通过NROWS维度进行迭代(
与freeBoard()
相同
此外,请注意,在这行
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
你更喜欢
board[i] = malloc(*widthPtr);
因为:
1( 没有必要铸造malloc和朋友
2(sizeof(char)
保证为1