Robin
Robin

Reputation: 737

dynamically allocate array of structs with C++

My problem is that I have a class, which should take a long int called "size", and use it to dynamically create an array of structs. The following compiles, but I get a runtime error that says the following:

error "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted

struct PageEntry
{
    ..some stuff in here
};

class PageTable {
public:
    PageTable(); //Default PageTable constructor.
    PageTable(long int size); //PageTable constructor takes arrival time and execution time as parameter
    ~PageTable(); //PageTable destructor.
    PageEntry *pageArray;
};

PageTable::PageTable(long int size)
{
    cout << "creating array of page entries" << endl;
    pageArray = new PageEntry[size];   //error occurs here
    cout << "done creating" << endl;
}

The error doesn't occur if I replace "size" with a number, ie. 10000. Any thoughts?

Upvotes: 0

Views: 1354

Answers (2)

Omnifarious
Omnifarious

Reputation: 56128

My guess is that when you call the function size somehow ends up being some ridiculously huge number or negative. Try printing it out inside the function and telling us what it is. You're probably running out of memory.

Also, stop using endl unless you mean it specifically instead of '\n'.

Upvotes: 2

Murali VP
Murali VP

Reputation: 6437

Is it possible that size could have been zero?

Upvotes: 0

Related Questions