Arg*_*gon 1 c arrays malloc pointers multidimensional-array
尝试创建一个二维数组并从 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)
Run Code Online (Sandbox Code Playgroud)
这是分配/释放的代码
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);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试制作一个指定宽度/高度的二维数组,这些数组是整数。在数组的每个部分中,将存储一个字符。
任何帮助都会很棒,谢谢。
for (i = 0; i < *widthPtr; i++)
{
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
}
Run Code Online (Sandbox Code Playgroud)
应该
for (i = 0; i < *heightPtr; i++)
{
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
}
Run Code Online (Sandbox Code Playgroud)
否则你迭代 NCOLUMNS 次(你想迭代 NROWS 维度)
同为 freeBoard()
另外,请注意,在这一行
board[i] = (char*)malloc((*widthPtr) * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
你比较喜欢
board[i] = malloc(*widthPtr);
Run Code Online (Sandbox Code Playgroud)
因为:
1)没有必要 cast malloc和朋友
2)sizeof(char)保证为 1