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;
}
tempCommandis an unitialisedchar*when:is called, causing the segmentation fault as
strcpy()will be writing somewhere it should not. Allocate memory fortempCommandbefore callingstrcpy():Remember to
free(tempCommand);when no longer required.There is no reason to cast the value of
*curTokenor*tempCommandto acharas that is already the type.