0

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?

Robin
  • 737
  • 2
  • 10
  • 23

2 Answers2

2

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'.

Omnifarious
  • 54,333
  • 19
  • 131
  • 194
  • thanks. that was definitely the problem. also, what does "endl" specifically mean? – Robin Mar 18 '11 at 02:45
  • @Robin: It says to insert a `'\n'` into the stream, then flush the buffer. It's the buffer flushing that's the problem. It frequently slows things down. If you're doing debugging output, use `cerr`, which always flushes. See this question for more details: http://stackoverflow.com/questions/2122986/why-does-endl-get-used-as-a-synonym-for-n-even-though-it-incurs-significant-pe – Omnifarious Mar 18 '11 at 04:02
  • If you're writing to console, why wouldn't you want to flush? – user666412 Mar 15 '18 at 19:20
  • @user666412 - It's a bad habit to get into. Also, who says you'll always be writing to the console. In Unix, it's common to redirect the input or output of a program. Precluding being able to do that efficiently seems very wrong. – Omnifarious Mar 16 '18 at 01:07
0

Is it possible that size could have been zero?

Murali VP
  • 6,198
  • 4
  • 28
  • 36