简体   繁体   中英

Segmentation Fault (core dumped) when using strcmp

I am making an application that registers client's cars and has some filtering options. I was able to do almost all of them with ease, but the filtering by model just won't work. If someone could guide me on what I'm doing wrong it would be much appreciated.

Complete code in gitlab: https://gitlab.com/salgadoth/car-ownership-in-c/-/blob/master/carownership.c

void listModel()
{
    int i, comp;
    char model[20];
    printf("\nTYPE IN DESIRED MODEL:\n");
    fflush(stdin);
    scanf("%s", &model);
    printf("DESIRED MODEL: %s\n\n", model);
    
    for(i = 0; i < counter; i++)
    {
        if(strcmp(model, car[i].model) == 0)
        {
            printf("\nBRAND: %s", car[i].brand);
            printf("\nMODEL: %s", car[i].model);
            printf("\nLICENSE PLATE: %s", car[i].license_plate);
            printf("\nYEAR OF FABRICATION: %d\n", car[i].year);
            printf("---------------------------\n");
        }
        else
        {
            printf("\nERROR - NO CAR FOUND");
            return 1;
        }
    }
}

You never initialize counter , so nothing stops your for loop from running into objects you didn't initialize. If model doesn't contain a valid string, then strcmp can fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM