Based on that code (a), here's what you need to check at a bare minimum:
- That
searchedcity
has enough space for the input (b).
- That all the strings held in the
citylist
linked list are properly constructed (null-terminated).
- That all those fields in the structure are actually character arrays (or equivalent pointers) rather than integers (population, for example).
- That the list itself is properly built (no dangling or invalid pointers).
You do have one other problem, though nothing to do with the segfault.
Your code will print "sorry, couldnt find that city"
for every node in the list that doesn't match your city so, if you have New York
, Moscow
and London
, and you look for London
, you'll get that message printed twice before it finds it.
A better solution (one of many variants) would be something like:
struct city *ptr = citylist;
while (ptr != NULL)
if (strcmp (searchedcity, ptr->name) == 0)
break;
if (ptr == NULL)
printf ("Sorry, couldnt find that city.\n");
else
printf ("%s, state = %s, pop = %s,r egion = %s, zip = %s\n",
ptr->name, ptr->statecode, ptr->population, ptr->region, ptr->zipcode);
That way, the loop is responsible for either finding the correct pointer or setting it to NULL. After the loop is the correct time to decide what should be printed.
(a) That code itself seems okay other than the dangerous scanf
but it does depend on quite a lot of other stuff not shown.
(b) In fact, scanf
with an unbounded %s
is a serious hole in your code that can easily lead to buffer overflow. See here for details and solution. In any case, scanf("%s")
is not a good way to scan strings with spaces in them since something like Los Angeles
would end up as Los
:-)