std::bad_alloc exception at large arrays

Hi community,

I encounter a problem with the allocation of large arrays.
If I allocate an array of almost 2GB memory an bad_alloc exception is thrown.

What is the problem? Any idea?

My system is Win 7 64bit, 8GB RAM.
But I'm compiling with the MS Visual Studio 32bit.
I wonder about that because I would expect this problem somewhere around the typical 32bit limit of 3.2GB.


Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;

void CreateMat(int ** &p, unsigned int r, unsigned int c)
{
	p = new int*[r];

	for(unsigned int i=0; i<r; i++)
		p[i] = new int[c];

	for (unsigned int i=0; i<r; i++)
	{
		for (unsigned int j=0; j<c; j++)
		{
			p[i][j] = (i+j)*(i+j);
		}
	}
}

int main()
{

	int **a = NULL;         // array
	unsigned int r = 23000;	// row number
                                // 22850 runs on my machine, 22900 does not
	unsigned int c = r;	// column number
	CreateMat(a,r,c);
	// plotting of used memory
	cout << "size in Byte: " << r*c*sizeof(a[0][0]) << endl;
	cout << "size in kB: " << r*c*sizeof(a[0][0])/1024 << endl;
	cout << "size in MB: " << r*c*sizeof(a[0][0])/1024/1024 << endl;
	system("pause");
	// free memory of array a
	for (unsigned int i=0; i<r; i++)
	{
		delete [] a[i];
	}
	delete [] a;
	cout << "deallocate array a" << endl;
	system("pause");

	return 0;
}
Last edited on
Does nobody has any idea what goes wrong?
> If I allocate an array of almost 2GB memory an bad_alloc exception is thrown.
> But I'm compiling with the MS Visual Studio 32bit.
> I wonder about that because I would expect this problem somewhere
> around the typical 32bit limit of 3.2GB.

Around the typical limit of std::numeric_limits<std::ptrdiff_t>::max()

1
2
3
4
5
6
7
8
#include <iostream>
#include <limits>

int main()
{
    std::cout << std::numeric_limits<std::ptrdiff_t>::max() << '\n' ;
    // 2147483647 with 32 bit pointers
}
Thank you JLBorges! That's exactly what I search for.
I just learned a lot about ptrdiff_t and size_t ;)
Topic archived. No new replies allowed.