[cfe-commits] Warning for bad std::string constructor invocations

Ingo Walther ingow at google.com
Mon Dec 5 09:08:57 PST 2011


This patch introduces two new warnings about bad std::string constructor
invocation. They can be turned on with -Wstring-constructor.

The first pattern it catches is:
std::string s('a', 10);

The intention probably was to call
std::string s(10, 'a');

which creates "aaaaaaaaaa". But implicit casts actually turn it into
std::string s(97, '\10');

The new warning says:

str.cc:6:17: warning: argument implicitly cast from 'char' to 'size_type'
(aka 'unsigned long') [-Wstring-constructor]
  std::string s('a', 10);
                ^~~
str.cc:6:17: note: did you mean to swap the two arguments?
  std::string s('a', 10);
                ^~~~~~~
                10, 'a'


The second pattern the patch catches is:
std::string v("abc", 10);

The constructor will read 10 characters into the new string, but there are
only four (including the null terminator). This reads junk if we're lucky,
and segfaults or opens security holes if we're unlucky.

The new warning says:
str.cc:9:17: warning: string literal is shorter than the number of
characters to read (3 vs 10) [-Wstring-constructor]
  std::string v("abc", 10);
                ^~~~~  ~~

If the literal is just one character long, we suggest to swap the arguments
and turn the string literal into a char literal:
str.cc:8:17: warning: string literal is shorter than the number of
characters to read (1 vs 10) [-Wstring-constructor]
  std::string u("a", 10);
                ^~~  ~~
str.cc:8:17: note: did you mean to swap the two arguments?
  std::string u("a", 10);
                ^~~~~~~
                10, 'a'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20111205/474674da/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: wstring-constructor.patch
Type: text/x-patch
Size: 15587 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20111205/474674da/attachment.bin>


More information about the cfe-commits mailing list