Point wind
Point wind

Reputation: 73

different behavior between gcc and clang in such code

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?

Upvotes: 6

Views: 221

Answers (1)

NathanOliver
NathanOliver

Reputation: 180990

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 = { ',', ';' }; 

Upvotes: 14

Related Questions