Reputation: 11
I have the problem with memory allocation in C++. Please take a look at the code below:
int main()
{
std::vector<BYTE *> v;
srand(GetTickCount());
// Load a document and free it.
int nDocSize = 1500;
while (nSize <= 1024 * 1024 * nDocSize)
{
int n = rand() % (1024 * 1024) + 1;
v.push_back(new BYTE[n]);
nSize += n;
}
for (auto itArr = v.begin(); itArr != v.end(); ++itArr)
{
delete[] * itArr;
}
// Load an image.
BYTE *data = new BYTE[1024 * 1024 * 500];
delete[] data;
return 0;
}
I'm allocating objects with the total size 1.5GB. The program crashes (bad_alloc exception) when after deallocation I'm trying to allocate an array with the size 500MB.
But this code will not crash for lower value of nDocSize, for example 500. Could you please explain me what causes bad_alloc exception here and how could I resolve this issue? I need so large array for an image loaded from PDF.
I use Visual Studio 2015 and It crashes for x86 application.
Upvotes: 1
Views: 1352
Reputation: 39
MSVC claims that any new statement requesting memory more than 0x80000000 would fail. By the way, allocating a whole large block of memory is also somewhat not acceptable, which is now proceeding by vector.
You may choose deque<>, it usually manages a series of continuous memory blocks, each block may be smaller, and extending its capacity is also cheaper. You can also manage memory yourself.
Upvotes: 1