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!
source to share
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).
source to share