-1

I'm studying code C on Linux.

I have a program to execute a command line which is typed from keyboard.

This is my code

char* command;
scanf("%s", command);
execl("/bin/sh", "sh", "-c", command, NULL);

and it print out nothing.

But the weird thing is: If a do not enter the command line from keyboard anymore and I assign value for the variable, then it work like this:

char* command;
command = "ls -l";
execl("/bin/sh", "sh", "-c", command, NULL);

Can anyone show me why my code doesn't work with scanf()

Thanks a lot!

2 Answers2

2
char* command;
scanf("%s", command);

memory is not allocated to command when scanf is being called so its leading to undefined behaviour, you should allocate memory by either

command = malloc(256);

or declare it as

char command[256];
Pras
  • 4,047
  • 10
  • 20
  • Sorry, this is a very bad practice. I'm really not saying this because I had the second answer but because readers of this question might think that this is the way to go, and it's simply not. There are lots of links about this like [this one](http://c-faq.com/stdio/scanfprobs.html) and [this one](http://c-faq.com/stdio/scanfprobs.html) and also [this one](https://stackoverflow.com/questions/26955466/difference-between-gets-vs-scanf-vs-fgets-in-c-programming?noredirect=1&lq=1). If you understand C, you know that not everything that works is the way to go. – SHG May 25 '17 at 06:44
0

scanf is used to read a char, not a string (it might work sometimes but it's really error-prone). use fgets from standard input instead.

Example:

char str[STR_LEN];
fgets(str, STR_LEN , stdin);

See this answer about the differences between them.

SHG
  • 2,516
  • 1
  • 14
  • 20