0

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;
    }
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Sean
  • 1,283
  • 9
  • 27
  • 43
  • `char **` is **no** array! – too honest for this site Sep 14 '15 at 20:10
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – too honest for this site Sep 14 '15 at 20:12

1 Answers1

1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    I cant believe i missed that, ofc args will be null on newline, just had to move the if statement up, thanks! – Sean Sep 14 '15 at 20:14