std::string add nullptr attribute
Jonny Grant
jg@jguk.org
Mon Feb 20 11:25:48 GMT 2023
On 20/02/2023 10:26, Xi Ruoyao wrote:
> On Sun, 2023-02-19 at 21:33 +0000, Jonny Grant wrote:
>
>> I noticed -Wanalyzer-null-dereference reports at build time a
>> dereference. Also works if a function parameter. I wondered why
>> std::string isn't detected by this static analyser option.
>
> Because the analyzer does not know the C++ standard disallows to use
> NULL here. It just analyzes the code. The code in libstdc++ reads:
>
> basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
> : _M_dataplus(_M_local_data(), __a)
> {
> // NB: Not required, but considered best practice.
> if (__s == 0)
> std::__throw_logic_error(__N("basic_string: "
> "construction from null is not valid"));
> const _CharT* __end = __s + traits_type::length(__s);
> _M_construct(__s, __end, forward_iterator_tag());
> }
>
> As you can see yourself, though the standard implies using NULL here is
> a UB, libstdc++ does not really code a UB here. So the analyzer will
> consider the code absolutely valid.
Thank you for your reply.
As you say, throwing logic_error seems rational if a NULL gets through to the constructor; if standard didn't imply creating an empty std::string when NULL was passed through.
> Note that throwing a C++ exception is not a programming error. It's
> perfectly legal to catch the exception elsewhere. It's also perfectly
> legal not to catch it and treat it as an abort() (calling abort is also
> not a programming error).
>
>
>> It's not pretty, but this wrapper catches NULL passed at compile time:
>>
>> std::string make_std_string(const char * const str)
>> {
>> // This line ensures: warning: dereference of NULL '0' [CWE-476]
>> [-Wanalyzer-null-dereference]
>> char b = *str;
>
> You are invoking an undefined behavior here if str is NULL, so it's
> essentially same as using a nonnull attribute for make_std_string.
Thank you for the suggestion, I gave that nonnull attribute a try, but it doesn't appear to warn for this example.
https://godbolt.org/z/boqTj6oWE
It should give a warning, as -fanalyzer enables -Wanalyzer-null-argument
https://gcc.gnu.org/onlinedocs/gcc/Static-Analyzer-Options.html
My preference would be to not have that char b = *str; maybe I would just do it within a macro enabled by a specific build
Just to share my first example, with that char b = *str; inside a macro.
https://godbolt.org/z/9Wo6zY3rT
Kind regards
Jonny
More information about the Gcc-help
mailing list