#include <iostream>
#include <memory>
#include <new>
using namespace std;
namespace foo {
#define BUFSIZE (10000)
char buf[BUFSIZE];
char *bufptr = buf;
int bufcount = 0;
void* getnewbuf(int size) {
if (size < 1) {
throw bad_alloc();
}
if (bufcount + size + sizeof(int) > BUFSIZE) {
throw bad_alloc();
}
int *len = reinterpret_cast<int*>(bufptr);
*len = size;
bufcount += sizeof(int);
bufptr += sizeof(int);
void *ptr = reinterpret_cast<void*>(bufptr);
bufptr += size;
bufcount += bufcount;
cout << "alloc: " << (size + sizeof(int)) << endl;
cout << "free: " << (BUFSIZE - (bufptr - buf)) << endl;
return ptr;
}
}
void* operator new (size_t t) { return foo::getnewbuf((int)t); }
void operator delete (void* p) { cout << "delete" << endl; }
struct Bar
{
static int cnt;
int zero[100];
int id;
Bar() : id(cnt++) { cout << "Bar(): " << id << endl; }
~Bar() { cout << "~Bar(): " << id << endl; }
};
int Bar::cnt = 0;
int main() {
// your code goes here
int *p = new int;
delete p;
Bar *bar = new Bar;
delete bar;
try {
Bar bbb;
auto_ptr<Bar> aaa(new Bar);
bar = new Bar[100];
delete [] bar;
}
catch (bad_alloc& e) {
cout << e.what() << endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWVtb3J5PgojaW5jbHVkZSA8bmV3Pgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKbmFtZXNwYWNlIGZvbyB7CgojZGVmaW5lIEJVRlNJWkUgKDEwMDAwKQpjaGFyIGJ1ZltCVUZTSVpFXTsKY2hhciAqYnVmcHRyID0gYnVmOwppbnQgYnVmY291bnQgPSAwOwoKdm9pZCogZ2V0bmV3YnVmKGludCBzaXplKSB7CglpZiAoc2l6ZSA8IDEpIHsKCQl0aHJvdyBiYWRfYWxsb2MoKTsKCX0KCWlmIChidWZjb3VudCArIHNpemUgKyBzaXplb2YoaW50KSA+IEJVRlNJWkUpIHsKCQl0aHJvdyBiYWRfYWxsb2MoKTsKCX0KCWludCAqbGVuID0gc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