Rohith Reddy Rohith Reddy - 1 year ago 78
C++ Question

Maximum number of objects in an array for a class

I have this class:

class tree
int row;
int column;

I want to create a total of around 1024 objects for the class
but if I increase the value to above 90 in
tree a[90]
it gives a
segmentation fault

tree a[90]; //Ok
tree a[1024]; //Segmentation fault

Is there a max limit on the number of objects we can create or is there any other work around to create 1024 objects in the form of an array?

Answer Source

Is there a max limit on the no. of objects we can create?

Well, yes. It's called the stack limit. It depends on how big your stack is. Your stack size here is:

stack_size = sizeof(int) * 2 * 90

If on your platform sizeof(int) is 4 (which it typically is), you have 4 * 2 * 90 = 720 bytes of stack, which seems very small.

Either way, the correct way of allocating large amounts of objects is on the heap, which typically has more space then the stack:

//std::vector allocates its elements on the heap
std::vector<tree> a(1024);

If you can't use std::vector for some reason, you can still use the old school style dynamic array (not recommended though):

tree* a = new tree[1024];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download