无法释放从函数返回的typedef结构

时间:2013-11-06 04:00:53

标签: c struct malloc free

我遇到了一个问题,这无疑是由于我的思维方面存在缺陷,但我似乎无法绕过它。我有一个像这样的结构:

typedef struct
{
    ALLEGRO_BITMAP *bitmap;
    char name[255];
    signed int  step;       // How many frames to move per cycle. Negative values will cause the animation to reverse. Affects "current" frame only.
    ANNE_SPRITE_CYCLES cycles;
    ANNE_SPRITE_ANIMATIONS anim;
    ANNE_SPRITE_FRAME current;
} ANNE_SPRITE; 

如果我是malloc()然后立即释放它,一切都没问题:

ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
free(sprite);
printf("Haven't crashed yet, boss!");

但是,如果我在函数内构建结构,如下所示:

ANNE_SPRITE anne_sprite_load(char sprite_name[]){
    ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
    //Snipped: a bunch of code to populate the struct with data
    return *sprite;
}

然后我不能在调用上下文中为爱或金钱释放结构:

ANNE_SPRITE test = anne_sprite_load("awesome_sprite");
free(test);

这会产生一个编译器错误 - 实际上我是passing 'ANNE_SPRITE' to parameter of incompatible type 'void *' - 但是我对于如何将这个变量精细化为一个格式free()准备使用而感到茫然。

2 个答案:

答案 0 :(得分:2)

ANNE_SPRITE* anne_sprite_load(char sprite_name[]){  // <== Change return type to be a pointer.
    ANNE_SPRITE *sprite = malloc(sizeof(ANNE_SPRITE));
    //Snipped: a bunch of code to populate the struct with data
    return sprite;  // <== Return the pointer.
}


ANNE_SPRITE* pTest = anne_sprite_load("awesome_sprite");  // <== Change to pointer type
free(pTest);  // <== Now free will work

答案 1 :(得分:2)

你的第二个例子返回ANNE_SPRITE(即结构,而不是指针)。 您应将签名更改为ANNE_SPRITE* anne_sprite_load(char sprite_name[])并调整return statement