2

I am trying to fix this code in C for an employee database. Employee can be searched by ID and if no record found then the 'Sorry record not found!' message is displayed.

void del() {
    char id[10];
    printf("\n\t Delete which record?:");
    gets(id);
    curr = start;
    if (strcmp(start->name, name) == 0) {
        start = start->next;
        free(curr);
        printf("\n\t First record deleted!");
        return;
    }

    while (curr) {
        if (strcmp(curr->next->name, name) == 0) {
            curr->next = curr->next->next;      
            printf("\n\n\t Record Deleted!");
            return;
        }
        curr = curr->next;
    }
    printf("\n\n\t Sorry record not found!");
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • See [Why is the `gets()` function too dangerous to be used?](http://stackoverflow.com/questions/1694036/) for reasons why you should not use `gets()`. If you use it, use a vastly bigger array than 10 characters (perhaps 4096, or 512 bytes; it still isn't safe though). Check the return value from it (or from `fgets()`, the recommended replacement) before using the result. It would help if you provided an MCVE ([How to create a Minimal, Complete, and Verifiable Example?](http://stackoverflow.com/help/mcve)), or at least the structure definition. Report errors on `stderr` and include the value. – Jonathan Leffler Jan 17 '16 at 04:39

1 Answers1

1

Instead of testing while (curr), you should test while (curr->next), otherwise you will dereference a NULL pointer when del does not find a matching record. This function will also fail if the database is empty, because you dereference start without first testing that it is non NULL.

Note that you should not use gets(). This function was removed from the latest C Standard, it cannot be used safely: your program will invoke undefined behavior if the user inputs more than 9 characters for the employee name.

Using a pointer to pointer, you can avoid special casing the initial list element:

void del() {
    char id[128];
    Employee **pp = &start;

    printf("\n\t Delete which record?: ");
    if (!fgets(id, sizeof id, stdin))
        return;
    id[strcspn(id, "\n")] = '\0'; /* strip the \n if present */

    while (*pp) {
        if (strcmp((*pp)->name, id) == 0) {
            Employee *p = *pp;
            *pp = p->next;
            free(p);  
            printf("\n\n\t Record Deleted!");
            return;
        }
        pp = &(*pp)->next;
    }
    printf("\n\n\t Sorry record not found!");
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189