Bad memory allocation in vector

Viewed 220

Have a look at this code:

int main()
{
    int m;
    cin >> m;
    vector<int> cnt(m +1,0);
}

Now if i take m=999999298(which is an int,right?). Why am I getting an"bad memory allocation" error in the vector?.

1 Answers
vector<int> cnt(m +1,0);

The declaration of vector you have tries to allocate 999999299 integer elements each of which has value 0. Considering the size of integer as 4 bytes, this is about 3.7 GB of memory. It appears that your application is not allowed that much memory. That is why you get the "bad memory allocation" error.

As to why there is such a limit, you can read this question and its answers.

Related