RoSsIaCrIiLoIA <n@esiste.ee> writes:
I'm reading a book on safety.
Do you know that?
printf("Use:> %s prog\n", argv[0] );
or
printf("Use:> %s prog\n", str_in_input);
is danger.
If str_in_input=" %x " this would print the return address of printf.
If str_in_input=" %x%x%x%x%x%x%x%x%x%x%x%x%x " it could see the stack.
and what If in the stack there is a pointer to a string password?
Either your book is incorrect, or you've misunderstood it. There is
an issue here, but your examples don't demonstrate it.
Here's a simple program that prints its first command-line argument,
if any, followed by a newline:
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc >= 2) {
printf("%s", argv[1]);
}
else {
printf("(no arguments)");
}
printf("\n");
return 0;
}
This is perfectly safe (at least for our current purposes).
Here's another version of the same program:
#include <stdio.h>
int main(int argc, char **argv)
{
if (argc >= 2) {
printf(argv[1]); /* DANGER!! */
}
else {
printf("(no arguments)");
}
printf("\n");
return 0;
}
On the line marked "DANGER!!", it uses an unchecked string as the
format argument to printf(). If I run this program with an argument
like "foobar" or "42", it will work exactly the same way as the first
version. If the argument happens to contain a printf format, though,
like "%s", it invokes undefined, because it tells printf() to look for
a second argument that wasn't actually passed to it.
The canonical first program contains the line
printf("hello, world\n");
It could instead be written as
printf("%s\n", "hello, world");
or
printf("%s", "hello, world\n");
but it really doesn't make any difference; since the format string is
a literal, we can tell by inspection that it doesn't contain any
conversion specifiers. If the string comes from an outside source,
such as the command line or standard input, we can't make that
assumption, so we need to use "%s" to guarantee that any specifiers
that happen to be in the string are just printed, not interpreted.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"