簡體   English   中英

從 NULL 構造字符串?

[英]constructing string from NULL?

在對代碼庫進行了一些更改后,我遇到了這個問題:

#include <string>

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

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

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

這會引發異常。 更改為“nullptr”沒有任何幫助(仍然沒有錯誤或警告)。

我想我的問題是,有沒有辦法在整個源代碼的預運行時檢測或找到這個錯誤? 也許是一些編譯器警告等(使用 MSVC VS-2017)

我最終修改了 basic_string 模板 ala。 basic_string(int) = delete; basic_string(::std::nullptr_t) = delete; - 這不會捕獲所有案例,但確實似乎至少可以捕獲直接案例

在示例文件上運行cppcheck (版本 1.89)會產生:

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

您可以添加幾個禁止使用的重載,以捕獲0NULLnullptr arguments 的使用:

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

如果您的編譯器支持,您可以添加一個蹦床 function 在編譯(和運行)時檢查 NULL 指針。 對於 GCC 它看起來像這樣:

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

}

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

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

您收到的警告是:

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

    test(NULL);
         ~~~~^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM