I'll get right to the point. I have a function that reads a command string from a socket, and then breaks that string into a struct:
typedef struct{
char* command;
char* option;
} Command;
If there is no option in the command string, Command.option = NULL
. For the purposes of this function, we can assume that the recv()'d data is validated on the other end of the socket.
Here is the function that I am having trouble with:
Command* getCommand(int cfd)
{
Command* commandStruct = (Command*) malloc(sizeof commandStruct);
char cmdStr[200];
char *running, *cmd, *option;
char* delimeters = " ";
memset(cmdStr, '\0', 200);
memset(commandStruct, '\0', sizeof(commandStruct));
if(recv(cfd, cmdStr, MAXLINE, 0) == -1) errExit("recv");
verbosePrint(opts.v, "recv'd: %s\n", cmdStr);
running = strdupa(cmdStr);
verbosePrint(opts.v, "copied string\n");
cmd = strsep(&running, delimeters); //SEGFAULT OCCURRING HERE. WHY?
verbosePrint(opts.v, "separated string\n");
//If the string is longer than the one command then there's an option
if(strlen(cmdStr) > strlen(cmd))
{
verbosePrint(opts.v, "recieved a command with an option");
option = strsep(&running, delimeters);
commandStruct->option = (char*) malloc(strlen(option));
strcpy(commandStruct->option, option);
}
commandStruct->command = (char*) malloc(strlen(cmd));
strcpy(commandStruct->command, cmd);
return commandStruct;
}
When I used GDB, I found the segfault occurred at cmd = strsep(&running, delimeters);
but I'm not sure why. GCC isn't warning me about invalid pointers, so I don't think that that is the problem. I strdup() as well so there shouldn't be any problems with writing over a literal or arrays or anything silly like that. I am honestly stumped.
Also, it only complains about strings that actually have a space in them (which is the delimiting character). Single word commands work fine. So I wonder if the problem is when strsep tries to write the space over with a '\0'? But why would that happen?