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
数组分配空间,所以我看不到它的工作(正如我所料,它没有用)。
我的错误是什么?
答案 0 :(得分:0)
当你这样做时
TRANSITION *transition = first->transitions;
将指针保存到内存中。然后释放内存,但这不会更改您在上面定义和初始化的指针变量transition
。因此,当您取消引用transition
时,您将访问未分配的内存,并且您有未定义的行为。
你必须记住,就像分配内存不会初始化已分配内存的内容一样,释放内存也不会对内存的内容做任何事情。因此,在释放它之后访问它时,它的一部分仍然可以保留其旧内容。