gpt4 book ai didi

c - 分段故障Strdup

转载 作者:行者123 更新时间:2023-11-30 17:45:10 26 4
gpt4 key购买 nike

我有一个程序,它读取一个字符串并将其分成三部分。第一部分是操作码,第二部分是数据,第三部分是 key 。

使用示例:

put this is stackoverflow

opcode: put
data: this is
key: stackoverflow

主要代码:

 int main(int argc, char **argv){
char command[MAX_MSG];
fgets(command, sizeof(command), stdin);
char *data;char *key;
command[strcspn (command, "\n")] = '\0';
char *aux_command_key = strdup(command);
char *aux_command_data = strdup(aux_command_key);
char *opcode = strtok(command, " ");
int success = 0;

if(strcmp(opcode, "put") == 0){
key = strdup(getKey(aux_command_key, opcode));
if(key == NULL){
printf("Invalid number of arguments.\n");
return -1;
}

else
data = getData(aux_command_data, opcode, key);
}
printf("opcode: %s\n",opcode);
printf("data: %s\n",data);
printf("key: %s\n",key);
free(aux_command_key);
free(aux_command_data);
}

我的问题是,当我在没有 key 的情况下运行程序时,它会给出段错误结果,而不是:“参数数量无效”。我不知道为什么会发生这种情况。谢谢。

最佳答案

您正在使用指令 put 调用 getKey,并且您说您没有在输入中提供足够数量的参数。因此,在我看来,getKey 将返回NULL。您无法使用 NULL 调用 strdup

我的建议:首先,调用getKey,然后,如果它不返回NULL,您可以复制它:

  if(strcmp(opcode, "put") == 0){
key = getKey(aux_command_key, opcode);
if(key == NULL){
printf("Invalid number of arguments.\n");
return -1;
}
else {
key = strdup(key);
data = getData(aux_command_data, opcode, key);
}
}

关于c - 分段故障Strdup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19716970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com