C++ exception: std::bad_alloc

Hi,

For simplicity, please consider this class with 3 attributes.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Human
{
public:
	int id;
	int age;
	std::string name;
};

int main()
{
	Human *h = new Human[120000]; <-- breaking
        return 0;
}


The error I am getting is
Unhandled exception at at 0x76ACC52F in Human.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x000D0EA8.

The machine where this program is running has 32 GB RAM and 1 TB Harddrive with paging on. Also, the Human class has about 350 attributes.

I am assuming this is a memory problem where the program doesn't have enough memory to complete the new operation. But 32 GB isnt a small memory size either.

Please let me know your thoughts in this matter and a probable resolution.

Thank you very much.
Well, as it stands, that doesn't seem a huge amount of memory (at least not when the strings are empty).

When I tested this, the structure itself required 12 or 48 bytes, depending on the compiler, and according to Process Explorer the memory usage during execution was 4.8 and 7.2 MB respectively. Of course if all of those strings were filled with data, that could add some more usage. In my test that took it to something over 100MB, but that still isn't excessive.

Does the simplified code posted here generate the error for you, or is it only when part of a larger program that it causes a problem?

Also, the Human class has about 350 attributes.

Are these simple types like int, or are there more strings, vectors etc.? You could try
 
    std::cout << "size of Human = " <<  sizeof (Human) << '\n';
to see how many bytes the struct itself uses - though objects such as std::string will add their own usage on top of that.
Last edited on
Thank you for your reply.
I checked the size of each object of Human (the real one) and it was coming out to 29 KB. With 120000, it was totaling to 3.48 GB.
The problem is that I was compiling it with a 32 bit compiler and that gave the error.
When I changed the compiler to 64 bit, it worked fine.
Thank you. The problem has been resolved.
Topic archived. No new replies allowed.