0

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?

user1112008
  • 432
  • 10
  • 27

2 Answers2

4

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.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • ahhhhh, I was trying `ss<<(!str ? 0 : str);` and it wasn't working – user1112008 Jun 03 '12 at 19:21
  • 1
    @user1112008: The implicit conditional operator return type is a common type to both its expressions, so in your case it would still return a null `wchar_t` pointer. – K-ballo Jun 03 '12 at 19:26
  • one more question, what if we are using templates? `template std::string realToString(type real)` and we to check if `real` isn't NULL? – user1112008 Jun 03 '12 at 19:37
  • @user1112008: Assuming `type` is a pointer, is still the same check. – K-ballo Jun 03 '12 at 19:40
  • `error C2440: '?' : cannot convert from 'const std::wstring' to 'bool'` something is wrong – user1112008 Jun 03 '12 at 19:44
  • 1
    @user1112008: What's wrong is that `const std::wstring` is not a pointer. Use regular function overloading to have a different implementation for pointers than non-pointers: `template std::string realToString(type real)` for the regular case, and `template std::string realToString(type* real)` for pointers. – K-ballo Jun 03 '12 at 19:48
2

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

if (str == NULL) {
    ss << 0;
} else {
    ss << str;
}
Matthias
  • 3,458
  • 4
  • 27
  • 46