0

I am attempting to store my char* parameter into a data member of a struct pointer. But I am receiving a Segmentation Fault: 11 when I attempt to do so.

void macro_set(char *name, char *body)
{
    verify(body != NULL, "null arg body");

    bool  nameExists = false;

    if(macro_list.name == NULL)
    {
        macro_list.name = Strdup(name);
        macro_list.body = Strdup(body);
    }
    else
    {
        struct macro *current = &macro_list;

        for(; current != NULL; current = current->next)
        {

          if(strcmp(name, current->name) == 0)
          {
              current->body = Strdup(body);
              nameExists = true;
          }
        }

        if(!nameExists)
        {
            current->name = Strdup(name);           
        } 
    } 
}

The error is occurring when I am trying to store name into current->name. Thanks to anyone that can help!

1 Answers1

3

If none of the macro_list elements matches name, then the for loop will exit with

nameExists = false and
current = NULL.

Then the subsequent if will be true, and the line

current->name = Strdup(name);

effectively assigns

((struct macro *) NULL)->name = Strdup(name);
Adam Liss
  • 47,594
  • 12
  • 108
  • 150