张鸿宇
张鸿宇

Reputation: 15

Some problem about the initialization of the vector

I can initialize the vector with 10^8,but I can't initialize it with 10^9.Why?

 vector<int> bucket;
 bucket.resize(100000000);      √ 
 bucket.resize(1000000000);     ×

Upvotes: 2

Views: 114

Answers (2)

J.R.
J.R.

Reputation: 1978

C++ vectors allocate memory in a contiguous block and it is likely that the operating system cannot find such a block when the block size gets too large.

Would the error message you are getting indicate that you are running out of memory?

The point is: Even if you think that you have enough memory left on your system, if your program's address space can not accommodate the large block in one chunk then you cannot construct the large vector (the maximum address space size may differ for 32-bit and 64-bit programs).

Upvotes: 1

YaleCheung
YaleCheung

Reputation: 620

It's because resize function will apply memory from heap. As you can figure that, the size will be 4000000000 bytes in your second resize operation, which is larger than the space your system could allocate(may be your computer couldn't find a piece of continuous space for you), and will cause exception and failure.

The maximum memory you can apply for depends on many reasons as follow:

  1. the hardware limitation of physical memory.
  2. the os bit(32 or 64)
  3. memory left for user. Operating system should meet the kernel's need first. Generally speaking, windows kernel needs more memory than linux or unix.
  4. ..

In a word, it is hard to know accurate memory size you can use, because it's a dynamic value. But you can make a rough estimation by new operator, and here is a good reference.

Upvotes: 3

Related Questions