Error on string '\0' null while concatenating

3

So I am trying to concatenate simple strings, and make a final sentence.

int main()
{
    string I ("I");
    string Love ("Love");
    string STL ("STL,");
    string Str ("String.");
    string fullSentence = '\0';

    // Concatenate
    fullSentence = I + " " + Love + " " + STL + " " + Str;
    cout << fullSentence;

    return 0;
}

Here, I didn't want to have "fullSentence" with nothing, so I assigned null and it gives me an error. There is no certain error message, except the following which I do not understand at all... :

Exception thrown at 0x51C3F6E0 (ucrtbased.dll) in exercise_4.exe: 0xC0000005: Access violation reading location 0x00000000. occurred

Soon as I remove '\0', it works just fine. Why does it so?

c++
string
null
asked on Stack Overflow Mar 22, 2019 by Sarah • edited Mar 22, 2019 by Keith Thompson

3 Answers

3

It appears to be an MSVC compiler bug to me.

The statement:

string fullSentence = '\0';

is not supposed to compile.


Indeed, there is no valid (implicit) constructor from char (i.e. '\0') to std::string. Reference Here.


Note that gcc and clang do not accept this code as valid. MSVC does.


Why does it so?

Looking at the assembly code, MSVC compiles that statement with the following constructor:

std::string::string(char const * const);

Passing '\0' as an argument, it will be converted into a nullptr actually.

So:

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range (for example, if s is a null pointer).

So your code is undefined behavior.

answered on Stack Overflow Mar 22, 2019 by Biagio Festa • edited Mar 22, 2019 by Biagio Festa
1

Put "\0" instead of '\0'. In C++ '' is for char and "" is for strings.

It's a conversion from char to non-scalar type std::string

answered on Stack Overflow Mar 22, 2019 by Thomas Swanson • edited Mar 25, 2019 by Ayxan Haqverdili
1

You could use a debugger to see a call stack of what happened. Looking into string class here Below constructor was called in your case:

basic_string( const CharT* s, const Allocator& alloc = Allocator() );

As per description of the constructor (emphasis mine) Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character. The behavior is undefined if [s, s + Traits::length(s)) is not a valid range

in your case range is empty -> invalid.

answered on Stack Overflow Mar 22, 2019 by David

User contributions licensed under CC BY-SA 3.0