Thread: Debugging an IF statement

  1. #1
    Registered User
    Join Date
    Dec 2009

    Debugging an IF statement

    Hi all,

    for my little program i need a check for input of "cd" the change direction command in linux.

    for some reason, this code is giving me a segmentation fault when myarray contains nothing...

    ie nothing was entered from the user.

    if(strcmp(myarray[0],"cd") == 0) 
    the code works...but when the array contains nothing it seg faults.

    any suggestions would be greatly appreciated.


  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    If by "empty" you mean an uninitialized local array like this:
    char array[10][32];
    That's because those could contain anything right now. So your strcmp is called on an uninitialized value. If there are no '\0' in it, strcmp() will go out of bounds.

    You can initialize to zero this way:
    char array[10][32] = {0};
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Feb 2010

    Re: Debugging an IF statement

    If you give the declaration statement of myarray it will easy to say answer.

    And you can check whether myarray[0] it is NULL or empty string.
    or try to print what value myarray contains.

    // If it is a pointer you can check like this.
    if(myarray[0]!=NULL && strcmp(myarray[0],"cd") == 0) 

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. issue with switch statement
    By bluetxxth in forum C Programming
    Replies: 14
    Last Post: 02-24-2010, 10:01 AM
  2. Dev-C++: Problems with Breakpoint Debugging
    By Thileepan_Bala in forum C Programming
    Replies: 1
    Last Post: 01-17-2008, 10:48 AM
  3. Usefulness of the "else if" statement
    By gn17 in forum C Programming
    Replies: 7
    Last Post: 08-12-2007, 05:19 AM
  4. Debugging book recommendation
    By dagans in forum Projects and Job Recruitment
    Replies: 1
    Last Post: 09-13-2005, 07:35 PM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM

Tags for this Thread