free()不接受结构类型

时间:2016-02-28 17:31:19

标签: c

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

typedef struct STATE STATE;
typedef struct TRANSITION TRANSITION;

struct STATE {
    char name[4];
    bool initial_state;
    bool final_state;
    TRANSITION *transitions;
    int numberTransitions;
};

struct TRANSITION {
    char c;
    STATE *destination;
};

STATE *create_state(char *name, bool is_initial, bool is_final);
void add_transition(STATE *source, char sign, STATE *dest);
void destroy_state(STATE **pp_state);

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

void add_transition(STATE *source, char sign, STATE *dest) {
    if (source->transitions == NULL) {
        TRANSITION *transitions = malloc(sizeof(TRANSITION));
        transitions->c = sign;
        transitions->destination = malloc(sizeof(STATE));
        transitions->destination = dest;
        source->transitions = transitions;
        source->numberTransitions = 1;
    } else {
        TRANSITION *transitions = source->transitions;
        int numberTransitions = source->numberTransitions;
        size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
        transitions = realloc(transitions, new_size);
        transitions[numberTransitions].c = sign;
        transitions[numberTransitions].destination = dest;
        (source->numberTransitions)++; 
    }
}

void destroy_state(STATE **pp_state) {
    TRANSITION *transitions = (*pp_state)->transitions;
    int numberTransitions = (*pp_state)->numberTransitions;
    int i = 0;
    for (i = 0; i < numberTransitions; i++) {
        free(transitions[i]);
        transitions[i] = NULL;
    }
}

我的例外是transitions[i]的类型与methods参数不兼容。该方法调用有什么问题?过渡是一种结构。

编辑:我添加了其他方法,因为它已被请求。

EDIT2:好的,我发现如果我的STATE只有一个TRANSITION,我可以释放TRANSITION指针。所以我的猜测是,当我尝试重新分配内存以进行额外的转换时,我在重新分配时出错了。

size_t new_size = sizeof(transitions) + sizeof(TRANSITION);
transitions = realloc(transitions, new_size);

4 个答案:

答案 0 :(得分:3)

free(transitions[i]);

transitions[i]不是要传递给free的任何指针类型。 transitions是指向结构的指针,但transition[i]变为结构变量(不是指针类型),因此不应传递给free

这样做 -

free(transitions);

答案 1 :(得分:1)

您无法从数组中释放单项(值)。

如果它的指针或免费的完整数组一次只能释放它所指的值:

       free(transitions);

或者将转换更改为指针数组,您可以执行前者:

 TRANSITION **transitions;

答案 2 :(得分:1)

规则是释放你拥有的malloc-ed。在这里,您重新分配了struts transition数组,而不是单个transition

所以在释放时,你必须使用:

free(transition);
顺便说一下,你传递给免费的内容必须是一个将被静默地转换为void *的指针。 transition是一个可以衰减到指针的数组,但transition[i]是一个结构,它不能转换为数组。这就是编译错误的含义。如果您使用free(&(transition[i]))free(transition + 1),则不会出现编译错误,但会调用未定义的行为,因为您尝试释放指向未通过malloc获取的内存的指针

答案 3 :(得分:0)

你不能free一个结构,你可以释放指针。释放内部STATE destination或整个transitions数组,或两者兼而有之。