我有一个带有两个char *指针的结构:
typedef struct{
char* command;
char* option;
} Command;
然后我有一个从套接字读取的函数,将数据分成两部分(命令和选项),然后填充结构以返回给调用者。但是,我在某个时刻遇到了段错误,我无法理解为什么。
这是我获得segfault信号的地方:
commandStruct->command = strdupa(cmd);
以下是我的变量的声明:
Command* commandStruct = malloc(sizeof(Command));
char *cmd, *option;
int cmdLen, optLen;
令我困惑的部分是,它只是一个简单的任务,它不应该是这么困难。我对C的细微差别非常不熟悉,所以有一个更有经验的程序员可能会抓到的显而易见的东西。任何帮助表示赞赏。
编辑:我已经调整了我的第一个malloc以便腾出空间而不仅仅是指针,但我仍然遇到麻烦。 Valgrind提到我正在编写8个坏字节,并且#34;地址0x0不是堆栈' d,malloc&d;或(最近)自由' d"。为了更加透明,我将在下面粘贴整个功能的副本,只是为了帮助它。
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;
}
答案 0 :(得分:4)
您的代码
Command* commandStruct = (Command*) malloc(sizeof(commandStruct));
正在分配空间。您正在分配足够的空间来存储指向Command而不是Command本身的指针。
尝试用
替换它Command* commandStruct = malloc(sizeof(*commandStruct));
这应该给你足够的空间。你也在为你正在存储的字符串分配空间。请考虑使用strdup。
希望这有帮助!