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..
}
That’s because
ROAD->next_citydoesn’t point to a valid address, it’s a dangling pointer.Try the following:
Is this what you originally intended to do?
Also, note that you should
freethe memory you acquire viamalloc.