SuperNoob
SuperNoob

Reputation: 178

Surprised by output

Compiled and ran the code below and was surprised by the output.

# include <iostream>

int main()
{
    const char* c="hello";

    for (size_t i=0; i<116; ++i)
    {
        std::cout << *(c+i);
    }
}

Output:

hellobasic_stringallocator<T>::allocate(size_t n) 'n' exceeds maximum supported sizeSt16nested_exception

Is this just undefined behavior or something else?

Upvotes: 1

Views: 63

Answers (1)

Blindy
Blindy

Reputation: 67362

It's something else: bad code leading to a buffer overflow. Your c has exactly 6 bytes allocated in the read only section it points to, yet you're trying to read past its end, which then triggers a look up for the first '\0' character.

Luckily for you, that character is so far away from the beginning of the string (c + 6) that the string allocator gives up.

Upvotes: 4

Related Questions