I'm trying to read from the keyboard something like a command
e.g.
start game,info1,info2
and I want to split and save those two strings, one having to do with what kind of command the user,types in and the other having information about the command.
I have done this so far, which reads and prints the separated by space strings but after that it hits me with this Segmentation fault (core dumped)
and the console program stops.
#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);
}
Compile
gcc cmd.c -o cmd.out
Output
./cmd.out
one two
one
two
Segmentation fault (core dumped)
I've tried other stuff as well but I'm keep getting the Segmentation fault, I'm really stuck. Any help would be greatly appreciated. Thanks