Rohith Reddy
Rohith Reddy

Reputation: 209

Maximum number of objects in an array for a class

I have this class:

class tree
{
public: 
    int row;
    int column;
};

I want to create a total of around 1024 objects for the class tree 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?

Upvotes: 1

Views: 907

Answers (1)

Rakete1111
Rakete1111

Reputation: 48958

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];

Upvotes: 3

Related Questions