- When using
printf()in theClanguage, using an incorrect format specifier can lead to unexpected behavior or program crashes. - For example,
printf("%s", l1);If you try to output a long-type variable to%s, you may get a runtime error.
- Here's an implementation of
safe_printf()that enables formatting inGCCandClang, and works fine inMSVC.
#include "safe_printf.h" // include header
int main()
{
long l1 = 10;
safe_printf( "%ld\n", l1 ); // ✅ Correct usage
// safe_printf( "%s\n", l1 ); // ❌ A Compile Warning occurs. (format mismatch)
return 0;
}- Detecting formatting errors in
GCC/Clang__attribute__((format(printf, x, y)))If there is incorrect formatting, a warning is raised at compile time.- For example,
safe_printf("%s", l1);Alert output.
- Can run securely even on
MSVCMSVCdoes not support__attribute__, so the compiler cannot detect errors, but it is configured to work without errors when executed.
- Processing
_snprintfcompatible withsnprintfMSVCuses_snprintfby default instead ofsnprintf, so it can be automatically mapped and run safely in a Windows environment.
- I have now implemented
safe_printf(), which is available inGCC,Clang, andMSVC.- If you use
GCC/Clang, invalid formatters can be detected at compile time. - Even on
MSVC,safe_printf()can run without problems. - In
Windows/Linux/macOSenvironments, you can provide safe output with the same code.
- If you use
- Now you can write more secure
Ccode without worrying about formatting errors when usingprintf()! 🚀
gccclangVisual C++