Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between an array and vector related to maximum size?

Tags:

c++

arrays

vector

When i run this code in my Devcpp compiler->

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> vec;
    for(int i=0;i<100000000;i++)
    vec.push_back(i);
}

It works even on run time. But when i run->

#include<bits/stdc++.h>
using namespace std;
int arr[1000000000];
int main()
{
    return 0;
}

It gives me link error.

As long as space is required both arr and vec requires the same space.Then why is it that vec code runs even fine on run time but arr code doesnt even compile.

like image 814
user3522401 Avatar asked Feb 01 '16 19:02

user3522401


1 Answers

The issue is with the allocation. In the first case, std::vector default allocator uses dynamic allocation, which in principle can allocate as much memory as you want (bounded of course by the OS and the amount of physical memory) whereas in the second case it uses the memory available for static allocation (technically the array has static storage duration), which in your case is smaller than 1000000000 * sizeof int bytes. See this for a nice answer regarding the various types of allocations in a C program (which also applies for C++).

Btw, avoid #include<bits/stdc++.h>, as it is non-standard. Include only the standard headers you need. One more issue: I don't think you get a compile-time error, you probably get a run-time error. In other words, the code compiles just fine, but fails to run.

like image 82
vsoftco Avatar answered Sep 30 '22 20:09

vsoftco