简体   繁体   中英

Problem in allocating memory for structure pointer

I have structure t_REC_instance and I want to create an instance and allocate memory for its variables. I am doing something wrong. In the commented space it gives sigINT error when debugging. Can some one point me what am i doing wrong.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);
}

The line

instance->currentRecipe =REC_Alloc();

is a problem because you're accessing the currentRecipe member of instance which doesn't exist; instance is not pointing anywhere, so you need to allocate it first:

instance = malloc(sizeof(t_REC_instance));

Fix:

Your code is assigning the currentRecipe member of the struct pointed to by instance , but instance is not set to anything, that means it's pointing to some invalid portion of memory which is causing the error.

Change this line:

t_REC_instance *instance;

to

t_REC_instance instance;

and this line:

REC_createInstance1(instance);

to

REC_createInstance1(&instance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM