Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 799
Point wind Avatar asked Oct 10 '18 17:10

Point wind


People also ask

What is the difference between Clang and GCC?

Clang is designed as an API from its inception, allowing it to be reused by source analysis tools, refactoring, IDEs (etc) as well as for code generation. GCC is built as a monolithic static compiler, which makes it extremely difficult to use as an API and integrate into other tools.

What is the difference between Clang and Clang ++?

The only difference between the two is that clang links against only the C standard library if it performs a link, whereas clang++ links against both the C++ and C standard libraries.

Does Clang optimize better than GCC?

Clang reduces the single-thread compilation time by 5% to 10% compared with GCC. Therefore, Clang offers more advantages for the construction of large projects.

What is the difference between Clang and LLVM?

Here Clang is the frontend and LLVM is the backend. LLVM defines a common intermediate representation (IR) based on the single static assignment (SSA) form. This makes many optimizations to be easily performed on the IR. It is also possible to add an LLVM IR pass to add custom optimizations.


1 Answers

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 = { ',', ';' }; 
like image 200
NathanOliver Avatar answered Oct 16 '22 09:10

NathanOliver