different behavior between gcc and clang in such code

  • A+
Category:Languages
int main()  {     std::vector<char> delimiters = { ",", ";" };       std::cout << delimiters[0]; } 

I get different answer between gcc and clang

clang7.0.0 print out ,

gcc8.2.0 gives the error

terminate called after throwing an instance of 'std::length_error' what(): cannot create std::vector larger than max_size()

Aborted

Which compiler is right?

 


Both compilers are correct because your code has undefined behavior.

You have fallen into a trap. { ",", ";" } is translated as a std::vector{const char*, const char*}. Since you have pointer this is valid syntactically (as it calls vector's iterator constructor), but you are using the address of two unrelated string literals which is not valid as the iterators have to point to the same container.

What you really need to get this to work is to use character literals, not string literals in the initializer list like

std::vector<char> delimiters = { ',', ';' };  

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: