Karavana
Karavana

Reputation: 487

Allocating memory for nested structure, segfault

So, I am trying to make a map for my class, I was practicing myself try to implement a nested loop to see if I take a "NewYork----250km------LosAngeles" kinda road, I should be able to give the NewYork as a previous city name and LosAngeles as a next city name. Distance is 250 km. I am taking the memory for the city name, road and city but after I type from the keyboard for the "next_city" part, I am getting segfault. Can someone please help me out what am I doing wrong?

typedef struct road road;
typedef struct city city;

struct city{
    int visited;
    int distance;
    int path;
    char *city_name;

};

struct road{
    int km;
    struct city *next_city, *previous_city;
};

int main()
{  

    char *a=malloc(sizeof(char)*10);
    char *b=malloc(sizeof(char)*10);

    city *NewYork = malloc(sizeof(city));
    NewYork->city_name = fgets(a,10,stdin); //this gives no error

    road *ROAD = malloc(sizeof(road));
    city *next_city = malloc(sizeof(city)); //to see if I can get a memory for LosAngeles

    ROAD->next_city->city_name = fgets(b,10,stdin); //but here it gives a segfault after I type the name to terminal..

}

Upvotes: 2

Views: 1453

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258688

That's because ROAD->next_city doesn't point to a valid address, it's a dangling pointer.

Try the following:

road *ROAD = malloc(sizeof(road));
city *next_city = malloc(sizeof(city));
ROAD->next_city = next_city; 

Is this what you originally intended to do?

Also, note that you should free the memory you acquire via malloc.

Upvotes: 3

Related Questions