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
strsep()sets token toNULLwhen no other delimiter is found. ThatNULLis then passed tostrdup(), causing your the segmentation fault.I removed the
while()insplit_command()(I assumed that it is a simplecommand arg) and added a check before the secondstrdup()and got it working. I also fixed some memory leaks:strinmain()and then overriding it withnewinsplit_command()losing the reference tostr.strdup()Moreover, you were freeing
cmd_infowhich is a buffer allocated statically on the stack.This is my version:
Remember that passing
NULLtoputs()and such leads to problems: always check forNULL!