gpt4 book ai didi

c - 释放结构体变量数组的内存

转载 作者:行者123 更新时间:2023-11-30 17:03:59 25 4
gpt4 key购买 nike

 typedef struct _TRANSITION TRANSITION;

typedef struct {
char name[4];
bool is_initial;
bool is_final;
TRANSITION *transitions;
int number_transitions;
} STATE;

struct _TRANSITION {
char c;
STATE *dest;
};

void destroy_state(STATE **pp_state) {
if (pp_state != NULL && *pp_state != NULL) {
free((*pp_state)->transitions);
(*pp_state)->transitions = NULL;
}
free(*pp_state);
*pp_state = NULL;
}

我想要做的是删除一个STATE。所以我需要释放我所在州拥有的所有 TRANSITION 。在这里您可以看到创建这些结构的函数:

STATE *create_state(char *name, bool is_initial, bool is_final) {
STATE *state = (STATE *) malloc(sizeof(STATE));
if (state != NULL) {
strcpy(state->name, name);
state->is_initial = is_initial;
state->is_final = is_final;
state->transitions = NULL;
state->number_transitions = 0;
}
return state;
}

void add_transition(STATE *source, char sign, STATE *dest) {
if (source != NULL && dest != NULL) {
TRANSITION *transitions = source->transitions;
TRANSITION *trans = source->transitions;
int i;
if (transitions != NULL) {
transitions = (TRANSITION *) realloc(transitions, sizeof(TRANSITION) * ((source->number_transitions) + 1));
} else {
transitions = (TRANSITION *) malloc(sizeof(TRANSITION));
}
trans = (transitions + source->number_transitions);
trans->c = sign;
trans->dest = dest;
(source->number_transitions)++;
source->transitions = transitions;
}
}

但是,当我用以下方法在 main 方法中测试我的函数时:

STATE *first = create_state("S'0", true, false);
STATE *second = create_state("S'1", false, false);
printf("%s: Initial: %d, Final: %d\n", first->name, first->is_initial, first->is_final);
add_transition(first, 'A', second);
add_transition(first, 'B', second);
add_transition(first, 'C', second);
TRANSITION *transition = first->transitions;
printf("%c", transition[0].c); // Output: A
printf("%c", transition[1].c); // Output: B
printf("%c\n", transition[2].c); // Output: C

destroy_state(&first);

printf("%c", transition[0].c); // Output:
printf("%c", transition[1].c); // Output: B
printf("%c", transition[2].c); // Output: C

看起来我刚刚删除了第一个 TRANSITION (输出对 printf() 函数进行了注释)。

显然我做错了什么。我对这个问题的第一个解决方案是我必须迭代转换。但由于我只是为一组 TRANSITION 分配空间,所以我看不到它起作用(正如我所期望的那样,它不起作用)。

我的错误是什么?

最佳答案

当你这样做时

TRANSITION *transition = first->transitions;

您将指针保存到内存中。然后释放内存,但这不会更改您在上面定义和初始化的指针变量 transition。因此,当您取消引用transition时,您会访问未分配的内存,并且会出现未定义的行为

您必须记住,就像分配内存不会初始化已分配内存的内容一样,释放内存也不会对内存的内容执行任何操作。因此,在释放它后访问它时,它的部分内容可能仍然保留其旧内容。

关于c - 释放结构体变量数组的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35961527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com