Search code examples
cstring-parsing

Parseing a C string (user input via console) with C string functions - segmentation fault


I'm trying to write a function that parses a string (a char *) character at a time but for some reason I am receiving a segmentation fault. I'm trying to read in user input and have it parsed for the program name and the arguments but that's somewhat irreverent.

Console:

>./mish 
>mish>ls
>command start:ls 
>*tempCommand:l 
>bottom
>Segmentation fault

Code:

    ParserData parseCommand(ParserData parserData, char* command)
    {
        char* tempCommand;
        char* currToken = '\0';
        short firstSpace = 0;

        printf("command start:%s \n", command);

        strcpy(tempCommand, command);

        while(*tempCommand)
        {
            printf("*tempCommand:%c \n", *tempCommand);

            if((char)*tempCommand == ' ' && firstSpace == 0)
            {
               printf("currToken: %c \n", (char)*currToken);
               strcpy(parserData.myChildProgramName,currToken);
               printf("after:");
               currToken = '\0';
               firstSpace = 1;
            }
            else if((char)*tempCommand != ' ' && *tempCommand != '-')
            {
              //strcat(currToken, tempCommand); 
            }

            printf("bottom\n");

            printf("currToken: %c \n", *currToken);

            tempCommand++;

       }

       printf("out\n");
       parserData.myChildProgramArguments = currToken;

      return parserData;
   }

Solution

  • tempCommand is an unitialised char* when:

    strcpy(tempCommand, command);
    

    is called, causing the segmentation fault as strcpy() will be writing somewhere it should not. Allocate memory for tempCommand before calling strcpy():

    tempCommand = malloc(strlen(command) + 1); /* +1 for terminating null. */
    if (tempCommand)
    {
        /* Use 'tempCommand' */
    }
    

    Remember to free(tempCommand); when no longer required.

    There is no reason to cast the value of *curToken or *tempCommand to a char as that is already the type.