Search code examples
cpointerslinked-listsingly-linked-listfunction-definition

Segmentation Fault ERROR: problem with adding multiple fields at once to linked list


void addContact(Contact **head)
{
    Contact *newContact; 
    Contact *currentNode;
    char listFieldsName[][30] = {"First Name", "Middle Name", "Last Name", "Company", "Phone", "Email", "Address", "Birthday", "Website", "Note"};
    int count = sizeof(listFieldsName) / sizeof(listFieldsName[0]);
    int id = 0;

    while (id <= count)
    {
        newContact = (Contact *)malloc(sizeof(Contact));
        if (id == count)
        {
            newContact = NULL;
        }
        else
        {
            newContact->fieldsName = listFieldsName[id];
            getString(newContact->fieldsValue, 30, listFieldsName[id]);
            newContact = newContact->next;
        }
        id++;
        if (*head == NULL)
        {
            *head = newContact;
        } else {
            newContact->next = *head;
            *head = newContact;
        }
    }

    currentNode = *head;
    while (currentNode->next != NULL)
    {
        printf("%s: %s\n", currentNode->fieldsName, currentNode->fieldsValue);
        currentNode = currentNode->next;
    }
}

I'm needing to add field feature to my program, so my idea is to create a linked structure with 2 variables fieldName and fieldValue but my code is working properly until i assign newContact->next = *head; (Error: Segmention fault)


Solution

  • This code snippet

        newContact = (Contact *)malloc(sizeof(Contact));
        if (id == count)
        {
            newContact = NULL;
        }
    

    already produces a memory leak.

    This statement

    newContact->fieldsName = listFieldsName[id];
    

    is invalid. It is even unimportant how the data member fieldsName is declared because the array listFieldsName is a local array that will not be alive after exiting the function.

    You need to copy the string stored in the array listFieldsName[id] using standard C function strcpy.

    In any case the statement above does not make sense.

    The data member next of the new allocated node was not initialized. So this statement

    newContact = newContact->next;
    

    invokes undefined behavior.

    You need to rewrite the function anew.