0

I have a function to add a new contact and store it in a file, also it will be stored in a linked list. I have a do/while loop to check if the phone Number that user entered is already available but I'm having a segmentation fault at this loop

void addContact(contactPtr *sPtr)
{
    FILE *fptr;
    contactPtr checkPtr = *sPtr;
    contactPtr crntPtr=checkPtr;
    contactPtr prevPtr;
    contactPtr newPtr;
    int check = 0;

    newPtr = (Contact *)malloc(sizeof(Contact));
    printf("Enter contact name: ");
    fflush(stdin);
    gets(newPtr->name);

    do
    {
        checkPtr=crntPtr;
        check=0;
        printf("Enter contact number: ");
        fflush(stdin);
        gets(newPtr->phoneNum);
        for (checkPtr; checkPtr != NULL; checkPtr = checkPtr->next)
        {
            if (strcmp(checkPtr->phoneNum, newPtr->phoneNum) == 0)
            {
                printf("Phone No is already available\n");
                check = 1;
                break;
            }
        }
    } while (check);

    fprintf(fptr, "\n%s\n", newPtr->name);
    fprintf(fptr, "%s\n", newPtr->phoneNum);

    checkPtr = crntPtr;
    while (checkPtr != NULL)
    {
        crntPtr = checkPtr;
        checkPtr = checkPtr->next;
    }
    while (crntPtr != NULL && (strcmp(newPtr->name, crntPtr->name) > 0))
    {
        prevPtr = crntPtr;
        crntPtr = crntPtr->next;
    }
    if (prevPtr == NULL)
    {
        newPtr->next = *sPtr;
        *sPtr = newPtr;
    }
    else
    {
        prevPtr->next = newPtr;
        newPtr->next = crntPtr;
    }
}
chro1104
  • 5
  • 3

1 Answers1

0
FILE *fptr;

You never opened a stream to a file, where fptr is pointing to.

Using:

fprintf(fptr, "\n%s\n", newPtr->name);
fprintf(fptr, "%s\n", newPtr->phoneNum);

invokes undefined behavior then.

Open a file with fopen() and check whether the returned value is a null pointer in which case we have an error routine:

FILE *fptr = fopen("file.txt", "w");
if (!fptr)
{
    perror("fopen() failed");
    exit(EXIT_FAILURE);
}

Furthermore you need to close a stream by fclose(fptr); when no longer needed.


To flush stdin with fflush(stdin); invokes under the most implementations also undefined behavior.

Using fflush(stdin) with especially this answer explains it perfectly.


gets() should never be used. It is dangerous. Use fgets() instead.

Why is the gets function so dangerous that it should not be used?