Difference between array and vector related to max size?

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 at runtime. But when I launched β†’

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

This gives me a communication error.

As long as space is required, both arr and vec require the same space. Then why does vec code work even fine at runtime, but arr code doesn't even compile.

+7
c ++ arrays vector
source share
2 answers

The problem is distribution. In the first case, std::vector default allocator uses dynamic allocation, which in principle can allocate as much memory as you want (limited, of course, by the operating system and the amount of physical memory), while in the second case it uses the memory available for static distribution (technically, the array has a static storage duration ), which in your case is less than 1000000000 * sizeof int bytes. See this one for a nice answer regarding the different types of distributions in a C program (which also applies to C ++).

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

+9
source share

It seems that the object

 int arr[1000000000]; 

too large to match the global data of your program for your environment. I am not getting a compile-time error, but I also get a temporary error message in my environment (cygwin / g ++ 4.9.3).

Decreasing the size by one tenth of the job for me. This might work for you too. I do not know how you can determine the maximum size of objects that can fit into global data.

The space available on the stack is the smallest in size.
The space available in global data is more than that. The space available on the heap is the largest of all.

If your object is too large to push it onto the stack, try entering global data.
If your object is too large to fit global data, use a heap.

+3
source share

All Articles