Reputation: 337
I'm trying to read user input on an infinite loop in a C program. The function that does this is as below.
void processUserInput(unsigned int io, char* cmd, char* buffer){
char* usrInput;
int rbytes;
if ((rbytes = read(io, buffer, 256)) < 0) {
perror("Read error: ");
exit(-1);
}
buffer[rbytes-1] = 0;
usrInput = (char*) calloc(256, sizeof(char));
strcpy(usrInput, buffer);
cmd = strtok(usrInput, " ");
}
In my main, this is what I do.
char buffer[256];
char* cmd = NULL;
processUserInput(STDIN_FILENO, cmd, buffer);
if(strcasecmp(cmd, "quit") == 0){
breakTrigger = 1;
}
memset(buffer, 0, 256);
The code gives a segmentation fault
the moment I enter an input on STDIN.
Any help appreciated.
Upvotes: 1
Views: 165
Reputation: 134396
The issue you're having is to write
cmd = strtok(usrInput, " ");
This is not storing the content of the returned pointer into cmd
. Therefore, in main()
, your cmd
remains NULL
. Later, the call to strcasecmp()
creates UB because of NULL
pointer.
You need to
cmd
in main()
, before passing that to processUserInput()
.strtok()
strcpy()
the returned token to cmd
.Also, as a side-note, please see this discussion on why not to cast the return value of malloc()
and family in C
..
Upvotes: 2
Reputation: 2566
because of the parameter type of cmd. In processUserInput, cmd is a pointer to a char (string), so, you can change what cmd points to, but cmd will not be changed when method returns. You should either call processUserInput with &cmd, and within processUserInput do *cmd = strtok(...), or better yet, just have processUserInput return cmd.
char* processUserInput(unsigned int io, char* buffer){
char* usrInput;
int rbytes;
if ((rbytes = read(io, buffer, 256)) < 0) {
perror("Read error: ");
exit(-1);
}
buffer[rbytes-1] = 0;
usrInput = (char*) calloc(256, sizeof(char));
strcpy(usrInput, buffer);
return strtok(usrInput, " ");
}
char buffer[256];
char* cmd = processUserInput(STDIN_FILENO, buffer);
Upvotes: 2