constructing string from NULL?

那年仲夏 提交于 2019-12-08 19:20:59

问题


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


回答1:


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

Checking test.cpp ...
test.cpp:9:10: error: Null pointer dereference [nullPointer]
test(NULL);
     ^



回答2:


You can add a couple of prohibited overloads capturing use of 0, NULL or nullptr arguments:

void test(int bad_argument) = delete;
void test(::std::nullptr_t bad_argument) = delete;



回答3:


You can add a trampoline function that checks for NULL pointer at compile (and run) time, if your compiler supports it. For GCC it would look like this:

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

}

void test(const char* ptr  __attribute__((nonnull))) {
    test(std::string(ptr));
}

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

The warning you get is:

<source>:13:14: warning: null passed to a callee that requires a non-null argument [-Wnonnull]

    test(NULL);
         ~~~~^


来源:https://stackoverflow.com/questions/58304063/constructing-string-from-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!