Sean
Sean

Reputation: 1313

C Segment Fault on char** Array

I am unsure why I am receiving a segmentation fault when my program hits the first if statement.

This is a method in a simpleShell program that's sole purpose is parsing stdin input stored in cmd and parse by whitespace into separate arguments in args

It will never print the if statement

void parseCmd(char* cmd, char** args)
{       
    int i;


    printf("----------> Parsed here \n");
    for(i = 0; i < MAX_LINE; i++) {
        args[i] = strsep(&cmd, " ");

        if (args[i][0] == '-') {
            printf("I was here... \n");
        }


        if(args[i] == NULL) break;
    }
}

Upvotes: 0

Views: 63

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

You're missing two obvious NULL checks.

  1. Check for NULL against args
  2. Check for NULL in strsep() return value.

Otherwise, you may very well attempt a NULL pointer deference in either case which results in undefined behavior.

Upvotes: 1

Related Questions