- When using
printf()
in theC
language, 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 inGCC
andClang
, 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
MSVC
MSVC
does not support__attribute__
, so the compiler cannot detect errors, but it is configured to work without errors when executed.
- Processing
_snprintf
compatible withsnprintf
MSVC
uses_snprintf
by 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
/macOS
environments, you can provide safe output with the same code.
- If you use
- Now you can write more secure
C
code without worrying about formatting errors when usingprintf()
! 🚀
gcc
clang
Visual C++
- MIT License
- https://github.com/JayTwoLab/safe_printf