SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard silver trophy redemption's Avatar
    Join Date
    Sep 2001
    Location
    Singapore
    Posts
    5,269
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    debugging segmentation fault

    I need some help finding out what's causing segmentation faults in a C program I wrote. I _think_ the problem lies in the code snippet below (the fault goes away when I comment out the code), though it can pretty much lie somewhere else in my 400+ lines of code.

    Can anyone spot whether this would cause a segmentation fault? And is my syntax correct, esp. assigning token to whatever's returned by strtok()?
    Code:
        char *token = {0};                  // stores token returned from strtok()
        char **commands;                    // array of separate commands in input line
    
    // snip
    
            /* tokenize the input line using | as separator */
            numOfProcs = 0;
            if ( (token = strtok(inputline, "|")) != NULL )
            {
                commands[numOfProcs] = strdup(token);
                numOfProcs++;
    
                while ( (token = strtok(NULL, "|")) != NULL )
                {
                    commands[numOfProcs] = strdup(token);
                    numOfProcs++;
                }
            }
    thanks!

  2. #2
    FreeBSD The Power to Serve silver trophy pippo's Avatar
    Join Date
    Jul 2001
    Location
    Italy
    Posts
    4,514
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How did you initialize char **commands; ?

    I would use something like:
    Code:
    #define MAX_COMMANDS 16
    
    char *commands[ MAX_COMMANDS ];
    then inside the loop I would check that numOfProcs will not reach the array limit.



    pippo
    Mr Andrea
    Former Hosting Team Advisor
    Former Advisor of '03

  3. #3
    SitePoint Wizard silver trophy redemption's Avatar
    Join Date
    Sep 2001
    Location
    Singapore
    Posts
    5,269
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes that was it. Thanks pippo.

    Interesting to note that the segmentation fault occurs on Linux, but not in cygwin.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •