Home > Mobile >  Checking if structure has values in c
Checking if structure has values in c

Time:07-18

I have the following linked list implementation:

typedef struct stringNode{
    char *key;
    char *value;
    struct stringNode *next;
} stringNode;

The linked list should start empty, so I initialize it with this:

stringNode *linkedList= (stringNode *)malloc(sizeof(stringNode));

Now, I want to add values to the list. This is done in a function. It is defined as

void setString(stringNode *linkedList, char *key, char *value{
    stringNode *p = linkedList;
    stringNode *newNode = (stringNode *)malloc(sizeof(stringNode));
    newNode -> key = key;
    newNode -> value = value;
    newNode -> next = NULL;
    while (p->next != NULL) {
        p = p -> next;
    }
    p -> next = newNode;
}

But, if the list is empty, then for some reason I get a segmentation fault that seems to come from accessing p -> next. I have also tried to check if p -> value is not null, and that also gives a segmentation fault. What am I doing wrong? And how do I fix it?

CodePudding user response:

You have defined values for newNode, but you never define initial values for linkedList (p). Therefore, the initial p->next will contain random garbage. Either ensure you set this to NULL the first time you allocate it, or if you are expecting things to be zero'd before using them, use calloc instead of malloc.

Calloc is slower than malloc, partially because it is zeroing.

  • Related