大小为8的无效读取。试图制作2D数组

问题描述 投票:1回答:1

[试图制作二维数组并从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数组,该数组是整数。在数组的每个部分中,将存储一个char。

任何帮助,都会很高兴,谢谢。

c arrays pointers multidimensional-array malloc
1个回答
5
投票
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)不需要cast malloc and friends

2)sizeof(char)保证为1

© www.soinside.com 2019 - 2024. All rights reserved.