C & C++

C & C++

Made by DeepSource

Use of nullptr with string_view CXX-W2053

Bug risk
Major

The std::string_view constructor that takes a const CharT* argument does not check for null pointers before dereferencing them. This can lead to undefined behavior. To prevent this, the code should be modified to use the default constructor of std::string_view in most cases where null pointers are passed.

In addition, the comparison operators for std::string_view cannot be used with a braced initializer list, so the code should be updated to use .empty() or the empty string literal for appropriate comparisons.

Bad Practice

std::string_view sv = nullptr;

sv = nullptr;

bool is_empty = sv == nullptr;
bool isnt_empty = sv != nullptr;

void accepts_sv(std::string_view);

void foo() {
    accepts_sv(nullptr);

    accepts_sv({{}});  // nullptr value used

    accepts_sv({nullptr, 0});  // nullptr value used, but with defined length
}

Recommended

std::string_view sv = {};

sv = {};

bool is_empty = sv.empty();
bool isnt_empty = !sv.empty();

void accepts_sv(std::string_view);

void foo() {
    accepts_sv("");

    accepts_sv("");  // fixed

    accepts_sv({nullptr, 0});  // no fix
}

References