Seg fault

This is a discussion on Seg fault within the C Programming forums, part of the General Programming Boards category; Code: static char *list_parse_switch(char *l,char *o,struct options *s) { char *nx = list_parse_item(l); int i; l = strltrim(l); for (i=0;i<s->n;i++) ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    1

    Seg fault

    Code:
    static char *list_parse_switch(char *l,char *o,struct options *s)
    {
      char *nx = list_parse_item(l); int i;
      l = strltrim(l);
      for (i=0;i<s->n;i++)
        {
          debug("%s %s\n",s->opts[i],l);
          if (strncmp(l,s->opts[i],strlen(s->opts[i]))==0) { *o = i+1; return(nx); }
        }
      return(NULL); }
    I have located the bug in the IF statement which causes application to go SEG FAULT. Any advices on how to modify it, so it would work good?

    Thanks in advance...
    Last edited by lihvar; 03-10-2006 at 03:34 AM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,313
    Things you need to ensure;

    1) s,l, and o all point to valid objects (eg they are not NULL and point to an array or value as expected by this function)
    2) l AND s->opts[i] are zero terminated

    It is desirable that l is shorter than s->opts[i] (or the third argument to strcmp is the minimum of strlen(s->opts[i]) and strlen(l)).

    I'm sure there are other possibilities I've missed.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,558
    1. Try to format your code better.
    return(NULL);
    The trailing brace should be on a new line in column 1

    2. Try to avoid single letter identifiers - i is OK for loops, but everything else should have meaningful names. Lower case l and i, along with numeric 1 all in the same code make for especially difficult reading.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting a seg fault
    By ammochck21 in forum C Programming
    Replies: 11
    Last Post: 01-23-2009, 04:27 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21