[cfe-commits] Undefined Behavior when invoking StringRef constructor on a null pointer

Matthieu Monrocq matthieu.monrocq at gmail.com
Sat Apr 30 03:18:06 PDT 2011


The  llvm::StringRef  class has a constructor taking a  const char*
parameter.

This constructor is extremely simple, and I am afraid too simple. It
directly invokes  ::strlen  on the parameter, without checking whether or
not the pointer is null or not.

Unfortunately as many C functions, strlen is not required by the standard to
check its input, and indeed popular implementations assume that the input is
not null, which results in undefined behavior.

As far as I see it, there are two ways to deal with this:
- using an assert, to check that the input is non-null. It does not
slow-down the program built with asserts disabled, but does not allow us to
invoke StringRef on null pointers
- using a simple inlined test (ternary operator ?:) to either invoke strlen
or set the length to 0. Makes migrating from  const char*  to
llvm::StringRef  easier.

I've used the second approach in the patch enclosed (which gmail thoroughly
refused to. I have not measured the performance impact though.

Please review.
Matthieu.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20110430/c3e7abb8/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: llvm_stringref_ub.diff
Type: application/octet-stream
Size: 542 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20110430/c3e7abb8/attachment.obj>


More information about the cfe-commits mailing list