Sarah
Sarah

Reputation: 191

Error on string '\0' null while concatenating

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?

Upvotes: 3

Views: 329

Answers (3)

tswanson-cs
tswanson-cs

Reputation: 116

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

Upvotes: 1

David
David

Reputation: 632

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.

Upvotes: 1

BiagioF
BiagioF

Reputation: 9715

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.

Upvotes: 3

Related Questions