Debugging an IF statement

This is a discussion on Debugging an IF statement within the C Programming forums, part of the General Programming Boards category; Hi all, for my little program i need a check for input of "cd" the change direction command in linux. ...

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    17

    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.

    Code:
    if(strcmp(myarray[0],"cd") == 0) 
    {
    	chdir(myarray[1]);
    }
    the code works...but when the array contains nothing it seg faults.

    any suggestions would be greatly appreciated.

    techevo

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    If by "empty" you mean an uninitialized local array like this:
    Code:
    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:
    Code:
    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
    Posts
    57

    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.

    Code:
    // If it is a pointer you can check like this.
    if(myarray[0]!=NULL && strcmp(myarray[0],"cd") == 0) 
    {
    	chdir(myarray[1]);
    }

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, 09:01 AM
  2. Dev-C++: Problems with Breakpoint Debugging
    By Thileepan_Bala in forum C Programming
    Replies: 1
    Last Post: 01-17-2008, 09: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, 03:49 PM

Tags for this Thread


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