Jon Tackabury
Jon Tackabury

Reputation: 49237

How to prevent a runtime crash when passing NULL to std::wstring?

I have a function like this:

void Test(std::wstring test1)
{
   cout << test1.c_str();
}

When I call it like this:

Test(NULL);

I get runtime exceptions like "invalid handle" and the entire program crashes. I can't do a null check on parameter 'test1' because the compiler says it can't be null. I'd like to either prevent a NULL from being passed in the first place, or have a way to check for NULLs at runtime. How can I solve this problem?

Upvotes: 1

Views: 1686

Answers (2)

bames53
bames53

Reputation: 88155

The specification for std::wstring says that you must not pass NULL to wstring's constructor. Doing so results in undefined behavior.

To avoid this you can overload your Test function such that passing NULL calls an overload that doesn't try to construct wstring from NULL.

void Test(wchar_t const *test1)
{
   if (test1)
     std::wcout << test1;
}

void Test(std::wstring const &test1) // added const & to avoid unnecessary copies
{
   Test(test1.data());
}

Now Test(NULL) will call the wchar_t const * overload and NULL will never be passed to the std::wstring constructor.

Upvotes: 1

Mark B
Mark B

Reputation: 96233

Unfortunately in this case you just have to write correct code: The null pointer is implicitly convertable to wstring (through the C-string constructor) and that constructor requires the C-string pointer to be non-null.

You have to do the null check prior to calling Test. You could implement an overload to help with this though:

void Test(const wchar_t* test1)
{
    if(test1) Test(std::wstring(test1));
}

Note that this may hide problems and you may want to assert in the overloaded Test function and/or simply fix the calling code so it never passes in an invalid string in the first place.

Upvotes: 7

Related Questions