#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2002
    Location
    Galway, Ireland
    Posts
    4
    Rep Power
    0

    Question 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++;
    }
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Oct 2000
    Location
    Back in the real world.
    Posts
    5,966
    Rep Power
    190
    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...
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2002
    Location
    Galway, Ireland
    Posts
    4
    Rep Power
    0
    thanks a million...that sorted the problem out for me:p

IMN logo majestic logo threadwatch logo seochat tools logo