I have a struct with two char* pointers:
typedef struct{
char* command;
char* option;
} Command;
I then have a function that reads from a socket, splits the data into two parts (command & option) then populates a struct to return to the caller. However, I get a segfault at one point and I can't understand why.
Here is where I get the segfault signal:
commandStruct->command = strdupa(cmd);
Here are the declarations of my variables:
Command* commandStruct = malloc(sizeof(Command));
char *cmd, *option;
int cmdLen, optLen;
The part that's confusing me is that it's just a simple assignment, it shouldn't be this difficult. I'm pretty unfamiliar with the nuances of C, so it could be something blatantly obvious that a more experienced programmer might catch. Any help is appreciated.
EDIT: I have adjusted my first malloc to make room for more than just a pointer, but I am still having trouble. Valgrind mentioned that I was writing 8 bad bytes and that "Address 0x0 is not stack'd, malloc'd or (recently) free'd". To be more transparent I'll paste a copy of the entire function below, just incase it helps.
Command* getCommand(int cfd)
{
Command* commandStruct = NULL;
char cmdStr[200];
char *cmd = NULL, *option = NULL;
int recieved, cmdLen, optLen;
commandStruct = malloc(sizeof(Command));
memset(cmdStr, '\0', sizeof(cmdStr));
memset(commandStruct, 0, sizeof(Command));
if(commandStruct == NULL)
{
fatal("sir, you malloc'd a null pointer. Memory problems?.\n");
}
if((recieved = recv(cfd, cmdStr, MAXLINE, 0)) == -1) errExit("recv");
verbosePrint(opts.v, "recv'd %u bytes: %s\n", recieved, cmdStr);
if(!strncmp(CMD_DIR, cmdStr, strlen(CMD_DIR)))
{
cmd = CMD_DIR;
option = NULL;
verbosePrint(opts.v, "set cmd to: %s\n", cmd);
}
else if(!strncmp(CMD_CHDIR, cmdStr, strlen(CMD_CHDIR)))
{
cmd = CMD_CHDIR;
option = &cmdStr[sizeof(CMD_CHDIR)];
verbosePrint(opts.v, "set cmd to: %s\n", cmd);
verbosePrint(opts.v, "set option to: %s\n", option);
}
else if(!strncmp(CMD_PWD, cmdStr, strlen(CMD_PWD)))
{
cmd = CMD_PWD;
option = NULL;
verbosePrint(opts.v, "set cmd to: %s\n", cmd);
}
else if(!strncmp(CMD_PUT, cmdStr, strlen(CMD_PUT)))
{
cmd = CMD_PUT;
option = &cmdStr[sizeof(CMD_PUT)];
verbosePrint(opts.v, "set cmd to: %s\n", cmd);
verbosePrint(opts.v, "set option to: %s\n", option);
}
else if(!strncmp(CMD_GET, cmdStr, strlen(CMD_GET)))
{
cmd = CMD_GET;
option = &cmdStr[sizeof(CMD_GET)];
verbosePrint(opts.v, "set cmd to: %s\n", cmd);
verbosePrint(opts.v, "set option to: %s\n", option);
}
commandStruct->command = strdupa(cmd);
if(option != NULL)
{
commandStruct->option = strdupa(option);
}
return commandStruct;
}