3 ms·
The trouble with printf-family functions is their variadic nature. If the arguments don't match the format string, you can wreak all sorts of havoc. A fun exer
by Aanok 6y ago
The trouble with printf-family functions is their variadic nature. If the arguments don't match the format string, you can wreak all sorts of havoc.
A fun exercise you can do is put a "%s" in the format string, omit the string argument and see what happens to the stack.
- anyfoo 6y agoThat's however relatively easy to verify programmatically, and indeed any recent compiler will complain about that. I'd say the usual trap is rather the size of the target buffer, because that requires bigger static analysis guns. (I'm ignoring things like "%n", because then you're playing with fire already.)
- Gibbon1 6y agoI think the big three C compilers have pragma's that you can tag printf/scanf with that will cause the compiler to verify the argument list.
- xxpor 6y ago__attribute__((format(printf, x, y))) for GCC: https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attributes.html https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attribut... There's options other than printf too.
- danaliv 6y agoThere's that, but with sprintf/vsprintf specifically, there's no way to keep it from storing characters past the end of your buffer. For example: char buf[2]; sprintf(buf, "%d", n); This will happily write to buf[2] and beyond if n is negative or greater than 9.