c++ – Std :: bad_alloc exception for 2 items


Why is the following program throwing a std::bad_alloc ?

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


You have a very interesting example. In this line: std::vector<char> delimiters = {",", ";"}; an attempt is made to create a vector from two iterators, since this is the only suitable constructor that the compiler can recognize in this initialization: {",", ";"} . Because the compiler thinks that it is given 2 iterators, then it tries to work with them, but in fact these are 2 independent pointers, working with which gives undefined behavior!

This is why you see an exception. The compiler, most likely, honestly subtracted the first from the second pointer, got some huge number, tried to allocate and got std::bad_alloc .

Scroll to Top