Avoid using snprintf where GCC can check sizes (#2121)

Interestingly, Clang's `-Wformat-overflow` seems to only warn
about buffers so small they will *always* underflow,
whereas GCC tries to infer whether they can overflow *at all*.
(I'm guessing they lean towards false-negatives and false-positives resp.)

Anyway, calling `sprintf` here remains safe, since GCC (notably, via CI)
checks our work, and it simplifies the code ever so slightly while
also providing an (admittedly negligible) performance improvement.

Note that there may be more locations where we could use `sprintf`,
but a cursory glance at our other uses of `snprintf` didn't seem fruitful.
(One way to test is to set the target buffer size to 1, and see if a
warning pops up for such a trivially-wrong size. If not, you can be certain
the compiler won't be able to help you with a more realistic size.)
This commit is contained in:
Eldred Habert
2026-09-19 03:15:07 +02:00
committed by GitHub
parent 142eae4558
commit 44328d522b
2 changed files with 30 additions and 7 deletions
+22
View File
@@ -66,4 +66,26 @@
#define _POSIX_C_SOURCE 200809L
#endif
// Apple has deprecated `sprintf` since Xcode 14 (for macOS 13), but we use it solely in
// contexts where both the size of the buffer *and* max size of the printed string are
// known statically, which GCC thus checks for.
#ifdef __APPLE__
#define sprintf_to_array(array, ...) \
do { \
static_assert( \
std::is_array_v<decltype(array)>, "Only use this macro to print to an array!" \
); \
snprintf(array, sizeof(array), __VA_ARGS__); \
} while (0)
#else
#define sprintf_to_array(array, ...) \
do { \
static_assert( \
std::is_array_v<decltype(array)>, "Only use this macro to print to an array!" \
); \
sprintf(array, __VA_ARGS__); \
} while (0)
#endif
#endif // RGBDS_PLATFORM_HPP