Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructing string from NULL?

Tags:

c++

string

c++17

After some change of the code-base I came accross this gotcha:

#include <string>

void test(const std::string& s){
}

int main()
{
    test(NULL);
    return 0;
}

https://godbolt.org/z/7uJnef

This throws an exception. Changing to 'nullptr' helps nothing (still no error or warning).

I guess my question is, is there a way to detect or find this error at pre-runtime throughout the sourcecode ? perhaps some compiler warning, etc. (using MSVC VS-2017)

I ended up modifying the basic_string template ala. basic_string(int) = delete; basic_string(::std::nullptr_t) = delete; - this won't catch all cases but does indeed seem to catch the direct cases at least

like image 913
darune Avatar asked Oct 09 '19 12:10

darune


1 Answers

Running cppcheck (version 1.89) on the example file yields:

Checking test.cpp ...
test.cpp:9:10: error: Null pointer dereference [nullPointer]
test(NULL);
     ^
like image 77
lubgr Avatar answered Sep 20 '22 00:09

lubgr