Helpful Information
 
 
Category: C Programming
problem with strtok in a loop

here I have some code which is assigning tokens taken from a string with strtok to an array called hops[][]. my problem is that once the loop has gone through the array, it's supposed to go on and do the same with another string.

However, as soon as the loop finishes and it reaches the last number in the string (in this case 17)...the program crashes.

anyone have any ideas? longstring has been read in from a text file if that's any use.





char buffer[20],
longstring[250],
hops[30][5];


/*longstring looks like: -host-1-2-3-4-5-6-7-.....-16-17-*/


strcpy(buffer, strtok(longstring, "-"));

printf("%s\n", buffer); /*prints host*/

if(0 == strcmp(buffer,"host"))
{
i=0;
while(strcpy(hops[i], strtok(NULL, "-"))!=NULL)
{
printf("%s\n", hops[i]); /*prints the digit*/
sleep(1);
i++;
}
}

i think on the last run you get a line like

strcpy(hops[i],NULL) which causes a segfault since you donīt try to copy an empty string but a null-pointer.

split your loop, you should see it in a debugger then...

thanks a million...that sorted the problem out for me:p










privacy (GDPR)