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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With