cpointersstructureprocedural-programming

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);
}

Solution

  • 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));