Search code examples
cstrcmpfault

Strcmp gives segmentation Fault


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct station 
{
    char * name;
    struct station * destinations;
    struct station * next;
} station;
struct station * findStation(station * stations, char * name)
{
    if(stations = NULL)
    {
        printf("ERROR");
        return NULL;
    }
    else
    {
        station * temp;
        for(temp = station; temp->next != NULL; temp = temp->next)
        {
            if(strcmp(temp->name, name) == 0)
            {
                return temp;
            }
        }
    return NULL;  
    }
}
void addStation(station ** stations, char * name)
{
    if(findStation(*stations, name) == NULL)
    {
        station * newstation;
        char name1[32];
        strcpy(name1, name);
        newstation = (station *)malloc(sizeof(station));
        newstation->name = &name1[0];
        if(*stations = NULL)
        {
            *stations = newstation;
        }
        else
        {
            newstation->next = *stations;
            *stations = newstation;
        }
    }
    else
    {
        printf("Station %s already exists.", name);
    }
}
void main(void)
{
    station * stations = NULL;
    stations = (station *)malloc(sizeof(station));
    char name[32], ch;
    strcpy(name, "Eindhoven");
    int h = 1;
    while(h == 1)
    {
        printf("Command (s/d/p/r/f/q): ");
        scanf(" %c", &ch);
        switch(ch)
        {
            case 's':
                printf("Station: ");
                scanf("%s", name);
                addStation(&stations, &name[0]);
                break;
            case 'q':
                h = 0;
                break;
            case 'p':

                break;
        }
    }
}

I need to write a program for school that makes a linked list of train stations and it's destinations. This piece of code gives me Segmentation Fault at "if(strcmp(temp->name, name) == 0)" (Line 23). I've been trying to fix this for like 5 hours but nothing works :(. Does anybody knows what's wrong?


Solution

  • You are basically setting stations = NULL and then doing something dereferencing it using temp. That's why the seg fault. Don't blame strcmp

    if(stations == NULL) // you were assigning here. 
    {
        printf("ERROR");
        return NULL;
    }
    

    And also

    for(temp = stations; temp->next != NULL; temp = temp->next)

    Few things to note (Good practice)

    Don't cast the return type of malloc. Also check the return value of malloc. Try to read reference of malloc and you would understand why.