Safe handling of string variables
Hello, I'm pretty new to C and in a nutshell I was doing the following as part of my class assignment:
foo (char *var) {
printf(var);
}
I was told that this is bad practice and unsafe, but I have not received detailed information about this from my mentor. I am guessing that if the var string is user-controlled it can be used to do bufferoverflow? How am I supposed to solidify this code? Do I need to limit the length of the string or something else?
Cheers and thanks!
You must use:
printf("%s", var);
instead of this. The way you have it, I could enter %s
as my input, and printf
- read a random chunk of memory as it was looking for a string to print. This can cause any unexpected behavior.
This is UNSAFE because it can lead to Format String Attack
Well, the first argument to printf is a format string. Thus, the calling function can pass:
foo("%d")
and then it printf
will look for an integer that is not there and cause undefined behavior. One possible fix for your function:
printf("%s", var);
which would have been printf
interpreted var
as a regular string (not a format).
Printf has the following signature:
int printf(
const char *format [,
argument]...
);
If the user enters format characters like% s all sorts of bad things will happen.
Use puts if you just want to output a string.