我正在尝试从键盘读取类似命令的内容,例如
start game,info1,info2
,我想拆分并保存这两个字符串,一个与用户输入的命令类型有关,另一个与命令有关。到目前为止,我已经完成了此操作,它读取并打印了由空格字符串分隔的字符串,但在那之后,我遇到了这个问题Segmentation fault (core dumped)
,并且控制台程序停止了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *command;
char *value;
} string;
string *allocate_memory();
void split_command(char* cmd_info, string **s);
int main(void) {
char cmd[255];
memset(cmd, 0, 255);
do
{
// read command
fgets(cmd, 255, stdin);
cmd[strcspn ( cmd, "\n")] = '\0';
string *str;
str = allocate_memory();
split_command(cmd, &str);
puts(str->command);
puts(str->value);
if(!strcmp(str->command, "start"))
printf("Starting...\n");
} while(strcmp(cmd, "exit"));
printf("Exiting the command line.");
return 0;
}
string *allocate_memory() {
string *p;
if( (p = (string *) malloc(sizeof(string))) == NULL ) {
printf("Memory allocation failed\n");
exit(1);
}
return p;
}
void split_command(char* cmd_info, string **s) {
string *new;
new = allocate_memory();
char *token;
while ((token = strsep(&cmd_info, " ")) != NULL)
{
printf("%s\n", token);
new->command = strdup(token);
}
new->value = strdup(token);
puts(new->value);
*s = new;
free(cmd_info);
}
编译
gcc cmd.c -o cmd.out
输出
./cmd.out
one two
one
two
Segmentation fault (core dumped)
我也尝试过其他东西,但我一直遇到分段错误,我真的被卡住了。任何帮助将不胜感激。谢谢