https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111102
Bug ID: 111102 Summary: illegal pointer arithmetic invoked by std::format("L{:65536}",1) Product: gcc Version: 14.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: gcc at pauldreik dot se Target Milestone: --- The following program: #include <format> constexpr auto blah = std::format(L"{:65536}", 1); is problematic when compiled with gcc 13 as well as the current trunk. It triggers a pointer arithmetic error inside https://gcc.gnu.org/git/?p=gcc.git;a=blame;f=libstdc%2B%2B-v3/include/std/format;hb=1d9454aba615eadd0d85c93713dd848227345f67#l295 it seems like the width is parsed into a unsigned short, but the return value is not checked in the case the format string was not a char string (as above, which is a wide char string). The following patch fixes the problem: commit 78ac41590432f4f01036797fd9d661f6ed80cf37 (HEAD -> master) Author: Paul Dreik <gccpatc...@pauldreik.se> Date: Tue Aug 22 19:16:57 2023 +0200 libstdc++: fix illegal pointer arithmetic in format when parsing a format string, the width is parsed into an unsigned short but the result is not checked in the case the format string is not a char string (such as a wide string). in case the parse fails, a null pointer is returned which is used for pointer arithmetic which is undefined behaviour. Signed-off-by: Paul Dreik <gccpatc...@pauldreik.se> diff --git a/libstdc++-v3/include/std/format b/libstdc++-v3/include/std/format index f3d9ae152f..fe2caa5868 100644 --- a/libstdc++-v3/include/std/format +++ b/libstdc++-v3/include/std/format @@ -285,7 +285,8 @@ namespace __format for (int __i = 0; __i < __n && (__first + __i) != __last; ++__i) __buf[__i] = __first[__i]; auto [__v, __ptr] = __format::__parse_integer(__buf, __buf + __n); - return {__v, __first + (__ptr - __buf)}; + if (__ptr) [[likely]] + return {__v, __first + (__ptr - __buf)}; } return {0, nullptr}; }