为结构指针分配内存的问题

问题描述 投票:0回答:2

我具有结构t_REC_instance,我想创建一个实例并为其变量分配内存。我做错了。在注释的空间中,调试时会出现sigINT错误。有人可以指出我在做什么错。c

typedef struct sAppRecipe
{
    union
    {
    struct sAppBread
        {
            int sugar_qty;
            int salt_qty;

        }tAppBread;
    struct sAppPancake
        {
            int sugar_qty1;
        }tAppPancake;
    };

}tAppRecipe;

typedef struct sAppRecipe tAppRecipe;


struct sREC_instance
{
    tAppRecipe *currentRecipe;
    tAppRecipe *newRecipe;
    tAppRecipe *updateRecipe;
};
typedef struct sREC_instance t_REC_instance;






tAppRecipe *REC_Alloc(void) {
    return malloc(sizeof (tAppRecipe));
}

t_REC_instance *instance;   // 

int REC_createInstance1(t_REC_instance *instance)
{

    instance->currentRecipe =REC_Alloc();      // there is a problem here
    if (!instance->currentRecipe)
        {
            printf("not allocated");
        }
}



void main()
{
REC_createInstance1(instance);
}
c pointers structure procedural-programming
2个回答
1
投票

instance->currentRecipe =REC_Alloc();

是一个问题,因为您正在访问不存在的currentRecipeinstance成员; instance没有指向任何地方,因此您需要先分配它:

instance = malloc(sizeof(t_REC_instance));


1
投票

修复:

您的代码正在分配currentRecipe所指向的结构的instance成员,但是instance未设置为任何东西,这意味着它指向了导致错误的内存的某些无效部分。

更改此行:

t_REC_instance *instance;

to

t_REC_instance instance;

和此行:

REC_createInstance1(instance);

to

REC_createInstance1(&instance);
© www.soinside.com 2019 - 2024. All rights reserved.