JayPhi JayPhi - 1 month ago 14
C++ Question

Differences in size of std::string_view of non-null terminated char array

I was playing around with std::string_view with different compilers and noticed that each compiler prints out different sizes when initiliazing the std::string_view with a non-null terminated char array.

It seems that every compiler prints out the correct size when turning on optimization but prints out the wrong size when optimization is off (except GCC, which prints out the correct size in both cases).

My question is: Why is this the case?

Code:

// test.cpp

#include <iostream>

#ifdef __MINGW32__
#include <experimental/string_view>
#elif _MSC_VER
#include <string_view>
#endif

int main()
{
const char foo[3]{ 'f','o','o' };

#ifdef __MINGW32__
std::experimental::string_view str_v{ foo };
#elif _MSC_VER
std::string_view str_v{ foo };
#endif

std::cout << sizeof(foo) << " " << str_v.size() << '\n';
}


Output: Visual C++ 19.00.24619.0

3 5 // cl /Zi /std:c++latest /EHsc /nologo /W4 test.cpp
3 3 // cl /O2 /std:c++latest /EHsc /nologo /W4 test.cpp


Output: Clang 4.0.0-r282394 (using MinGW-w64)

3 4 // clang++ -g --target=x86_64-w64-mingw32 -std=c++1z -Wall -o test.exe test.cpp
3 3 // clang++ -02 --target=x86_64-w64-mingw32 -std=c++1z -Wall -o test.exe test.cpp


Output: GCC 6.2.0 (MinGW-w64)

3 3 // g++ -g -std=c++1z -Wall -o test.exe test.cpp
3 3 // g++ -O2 -std=c++1z -Wall -o test.exe test.cpp

Answer

From the cppreference.com:

constexpr basic_string_view(const CharT* s);

Constructs a view of the null-terminated character string pointed to by s, not including the terminating null character.

You test program causes Undefined Behaviour, as T.C. has mentioned in the comment above.