C语言 无法释放结构中的整数数组

5fjcxozz  于 2023-01-04  发布在  其他
关注(0)|答案(1)|浏览(142)

我一直在尝试做一棵树,它有9个孩子,其中一些孩子没有初始化,所以实际上它是一棵可变数量的孩子的树。初始化的孩子的索引被放在一个数组中,数组的大小与树节点应该拥有的孩子的数量相同。在释放整个树的内存分配的同时,我也想释放那个数组。但是我遇到了一个问题,那就是由于某种原因,当我尝试这样做时,出现了一个错误。2这里是编译后完全可执行的代码片段,不过,如果有人愿意帮我调试的话。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct moveNode
{
    int rating;
    // char player;
    int numPossibleMoves, *possibleMoves;
    struct moveNode **children;
};

struct moveNode *moveTreeHead;
struct moveNode *createHeadNode(void);
void initializeNode(struct moveNode *node, char *boardState);

int main()
{
    moveTreeHead = createHeadNode();

    printf("moveTreeHead->possibleMoves[1] %d\n", moveTreeHead->possibleMoves[1]);
    free(moveTreeHead->possibleMoves);
}

void initializeNode(struct moveNode *node, char *boardState)
{
    int i, possibleMovesCounter = -1;
    node->numPossibleMoves = 0;
    for (i = 0; i < 9; i++)
    {
        if (boardState[i] != 'x' && boardState[i] != 'o')
        {
            node->numPossibleMoves++;
        }
    }

    if (node->numPossibleMoves != 0)
    {
        node->possibleMoves = (int *)malloc(sizeof *(node->possibleMoves));
        for (i = 0; i < 9; i++)
        {
            if (boardState[i] != 'x' && boardState[i] != 'o')
            {
                possibleMovesCounter++;
                node->possibleMoves[possibleMovesCounter] = i;
                node->children[i] = (struct moveNode *)malloc(sizeof *(node->children[i]));
                node->children[i]->numPossibleMoves = 0;
            }
        }
    }
    else
    {
        node->possibleMoves = NULL;
    }
}

struct moveNode *createHeadNode()
{
    struct moveNode *ret = (struct moveNode *)malloc(sizeof(struct moveNode));
    ret->children = (struct moveNode **)malloc(sizeof *(ret->children) * 9);
    initializeNode(ret, "012345678");
    return ret;
}

我收到以下调试错误消息:

warning: HEAP[helloworld.exe]:
warning: Heap block at 0000028AA9C23530 modified at 0000028AA9C23544 past requested size of 4

Thread 1 received signal SIGTRAP, Trace/breakpoint trap.
0x00007ffa1046a773 in ntdll!RtlRegisterSecureMemoryCacheCallback () from C:\WINDOWS\SYSTEM32\ntdll.dll

这到底是什么意思?我所要做的就是释放一个用malloc正确分配的整数数组。这里有什么问题?我甚至测试了一下,用printf("moveTreeHead->possibleMoves[1] %d\n", moveTreeHead->possibleMoves[1])创建的数组没有问题。
编辑:问题解决了,谢谢!!@UnholySheep

ruarlubt

ruarlubt1#

node->possibleMoves = (int *)malloc(sizeof *(node->possibleMoves));仅为一个int分配内存,但您以后可能会将其视为更大的数组@UnholySheep进行访问
其他:
各种分配中不需要的转换。

相关问题