Question

Cannot initialize a structure linked list I am getting a segmentation fault (core dumped) every time I set var into ftt.foods->head->data and I have no idea why it segfaults. If I malloc ftt inside BOOLEAN init(ftt_type * ftt) the type ftt will not get the memory can everyone tell me what is wrong with my program? and what if i need to malloc() in the init() function is it possible ?

struct food { char id[IDLEN + 1]; char name[FOODNAMELEN + 1]; char desc[DESCLEN + 1]; struct money price; };

struct ftt_node
{
    struct food * data;
    struct ftt_node * next;
};

struct ftt_list
{
    struct ftt_node * head;
    unsigned list_len;
};


/* data definitions for the coins array */

enum denomination
{
    FIVE_C,TEN_C,TWENTY_C,FIFTY_C,
    ONE_D,TWO_D,FIVE_D,TEN_D,TWENTY_D,FIFTY_D
};

struct coin
{
    enum denomination denom;
    unsigned count;
};

#define NUMDENOMS 10

/* header containing list and coins */

typedef struct ftt
{
    struct ftt_list * foods;
    struct coin coins[NUMDENOMS];
} ftt_type;



init fuction
        BOOLEAN init(ftt_type * ftt)
    {   
        printf("init_ftt values:%d",ftt);   
        memset(ftt->coins,0,(size_t)NUMDENOMS * sizeof(struct coin));
        printf("\n\n\n\nmemset count check:%d\n",ftt->coins->count);
        printf("\nmemset denom check:%d\n",ftt->coins->denom);
        /*memset(ftt->foods->listlen,0,IDLEN + 1);*/ 
        ftt->coins->count=0; 
        ftt->foods->list_len=0;
        memset(ftt->foods,0,sizeof(struct ftt_list));
        ftt->foods->head->data->price.dollars=100;
        ftt->foods->head->data->price.cents=100;



        printf("**************************************************can not set variable to ftt->foods->head->data->name*******************************\n\n");        strcpy(ftt->foods->head->data->id,"good");
        strcpy(ftt->foods->head->data->name,"good");
        strcpy(ftt->foods->head->data->desc,"good");
        ftt->foods->head->data->price.dollars=100;
        ftt->foods->head->data->price.cents=100;
        printf("\nmemset desc check:%s\n",ftt->foods->head->data->desc);

        return TRUE;
    }

main

 int main(int argc, char **argv)
{
    ftt.foods = (struct ftt_list *) malloc(sizeof(struct ftt_list)); 
    ftt.foods->head = (struct ftt_node *)malloc(sizeof(struct ftt_node));  
    ftt.foods->head->data=(struct food *)malloc(sizeof(struct food));
    ftt_type  ftt;

    init(&ftt);
    return EXIT_SUCCESS;
    }
Was it helpful?

Solution

In the init() function, you are doing

memset(ftt->foods,0,sizeof(struct ftt_list));

This will overwrite members of ftt->foods so you will loose memory allocated to ftt->foods->head.

So when you try to access ftt->foods->head->data you are accessing null pointer ftt->foods->head.

You should memset() before malloc() or rather use calloc().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top