0

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?

shermanzach
  • 591
  • 1
  • 6
  • 14
  • what's the return type for strsep function? Are you making sure the required type of parameters and the variable which is getting the output is valid type? – AKS Dec 06 '14 at 20:55
  • @arun strsep return a char*, which matches my assignment. Here's the prototype if it's helpful: `char *strsep(char **stringp, const char *delim);` and as far as I can tell I am matching the types correctly. – shermanzach Dec 06 '14 at 20:58
  • Basically, strsep does the following: First it finds a delimeter, then it replaces that with a null terminator, returns the new "terminated" string, then mutates the original string to point past the null terminator it just placed. More information can be found here: http://man7.org/linux/man-pages/man3/strsep.3.html – shermanzach Dec 06 '14 at 21:02

0 Answers0