[libcxx-commits] [PATCH] D103444: [libcxx] Don't use an undefined '+' in unsigned/octal/hexal print formats

Martin Storsjö via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Tue Jun 1 03:24:52 PDT 2021


mstorsjo created this revision.
mstorsjo requested review of this revision.
Herald added a project: libc++.
Herald added a reviewer: libc++.

If building code like this:

  unsigned long val = 1000;
  snprintf(buf, sizeof(buf), "%+lu", val);

with clang, clang warns

  warning: flag '+' results in undefined behavior with 'u' conversion specifier [-Wformat]

Therefore, don't construct such undefined format strings.

This fixes number formatting in mingw-w64 if built with
`__USE_MINGW_ANSI_STDIO` defined (there, the '+' flag causes a
leading plus to be printed when formatting unsigned numbers too,
while the '+' flag doesn't cause any extra leading plus in other
stdio implementations).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D103444

Files:
  libcxx/src/locale.cpp


Index: libcxx/src/locale.cpp
===================================================================
--- libcxx/src/locale.cpp
+++ libcxx/src/locale.cpp
@@ -4597,7 +4597,10 @@
 __num_put_base::__format_int(char* __fmtp, const char* __len, bool __signd,
                              ios_base::fmtflags __flags)
 {
-    if (__flags & ios_base::showpos)
+    if (__flags & ios_base::showpos &&
+        (__flags & ios_base::basefield) != ios_base::oct &&
+        (__flags & ios_base::basefield) != ios_base::hex &&
+	__signd)
         *__fmtp++ = '+';
     if (__flags & ios_base::showbase)
         *__fmtp++ = '#';


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D103444.348921.patch
Type: text/x-patch
Size: 612 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20210601/44ab3214/attachment.bin>


More information about the libcxx-commits mailing list