c - Allocating memory for nested structure, segfault -


so, trying make map class, practicing myself try implement nested loop see if take "newyork----250km------losangeles" kinda road, should able give newyork previous city name , losangeles next city name. distance 250 km. taking memory city name, road , city after type keyboard "next_city" part, getting segfault. can please me out 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 can memory losangeles      road->next_city->city_name = fgets(b,10,stdin); //but here gives segfault after type name terminal..  } 

that's because road->next_city doesn't point valid address, it's dangling pointer.

try following:

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

is intended do?

also, note should free memory acquire via malloc.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -