user1112008
user1112008

Reputation: 442

C++ wstringstream << NULL

I'm having an issue with wstringstream. When I'm doing this

    std::wstringstream ss;
    wchar_t* str = NULL;
    ss << str;

Application crashes with error

Unhandled exception at 0x53e347af (msvcr100d.dll) in stringstr.exe: 0xC0000005: Access violation reading location 0x00000000.

For example this works good:

ss << NULL;
wchar_t* str = L"smth";
ss << &str;

Not always str has value, it could be NULL sometimes and when it is NULL I would like to put 0 into stream. How to fix it?

Upvotes: 0

Views: 641

Answers (2)

K-ballo
K-ballo

Reputation: 81349

If it's null, don't output a null wchar_t pointer:

( str ? ss << str : ss << 0 );

Note that this won't work:

ss << ( str ? str : 0 )

since the implicit conditional operator return type is a common type to both its expressions, so it would still return a null wchar_t pointer.

Upvotes: 4

Matthias
Matthias

Reputation: 3556

Check before you output to the stringstream (as already suggested)

if (str == NULL) {
    ss << 0;
} else {
    ss << str;
}

Upvotes: 2

Related Questions