Read carefully scanf(3). Notice that with gcc -m32
you have sizeof(userInput)
equal to 4 (the size of all pointers is the same; without the -m32
it would be 8). So if the user is typing something like working
(or any input of four characters or more, not just one letter like a
), you have undefined behavior (because of a buffer overflow) and that is really bad. You probably should consider using getline(3) instead (or perhaps even readline(3)), e.g.
char* userInput=NULL;
size_t sizeInput= 0;
printf("Commands:\n");
/// put your other printfs here, then
ssize_t lengthInput = getline(&userInput, &sizeInput, stdin);
if (lengthInput < 0 || userInput==NULL)
{ perror("input error"); exit(EXIT_NULL); };
Now you have the entire typed line in userInput
(including the terminating newline) and you know that its length is lengthInput
. You can parse that line, perhaps using sscanf(3) (hint: use its return count, and consider using %n
) or just using other techniques (some strcmp
, or strtok(3)...). When done, you should free(userInput)
.
Notice that scanf
(or sscanf
) do not allocate any memory for parsed data, unless you use %ms
(which is probably POSIX specific). With %s
it always expecting some fixed length buffer, and for a array buffer declared char buf[64];
you'll better give the size with %63s
; BTW, you should always test the result count of scanf
. So you might code (after the above)
char nambuf[64];
if (sscanf(userInput, "a %63s", nambuf)==1) {
// use nambuf to add it
}
else if (sscanf(userInput, "r %63s", nambuf)==1) {
// use nambuf to remove it
}
(but the above is a bit silly, we read an arbitrary sized line but process nambuf
of at most 63 bytes). You could just use scanf
like if (scanf("a %63s", nambuf)==1)
without needing any userInput
.
Alternatively, you could use the Linux specific %as
or better the POSIX specific %ms
like:
char* nameptr=NULL;
if (scanf("a %ms", &nameptr)==1) {
then that successful scanf
would have malloc
-ed and filled nameptr
and you should later free(nameptr)
. If you want to accept only lowercase letters consider coding something like if (scanf("a %m[a-z]", &nameptr)==1)
etc...