Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading