Question #50784

In a main()demonstration function, declare a pointer to an array of 500 School objects
and include code to handle any memory allocation errors that occur. In a loop, declare 500
array objects at a time, continuing to rewrite the main()function if necessary until you
create enough School objects to cause a memory allocation exception. (Hint: You might
want to display a count periodically to assure yourself that the School objects are being
created.) When memory is exhausted, display an appropriate message and terminate the
application. Save the file as School.cpp.

Expert's answer

#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string>
#include <new>
class School{
private:
int schoolNumber;
public:
School(int _schoolNumber = 0) { schoolNumber = _schoolNumber;}
};
using namespace std;
int main(){
long int n = 500000000;
try{
School *shools = new School[n];
}
catch(bad_alloc& ex) {
cerr<<ex.what()<<endl;
system&#40;"pause"&#41;;
exit(1);
}
catch(exception& ex) {
cerr<<ex.what()<<endl;
system&#40;"pause"&#41;;
exit(1);
}
return 0;
}

LATEST TUTORIALS
APPROVED BY CLIENTS