fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <new>
  4. using namespace std;
  5.  
  6. namespace foo {
  7.  
  8. #define BUFSIZE (10000)
  9. char buf[BUFSIZE];
  10. char *bufptr = buf;
  11. int bufcount = 0;
  12.  
  13. void* getnewbuf(int size) {
  14. if (size < 1) {
  15. throw bad_alloc();
  16. }
  17. if (bufcount + size + sizeof(int) > BUFSIZE) {
  18. throw bad_alloc();
  19. }
  20. int *len = reinterpret_cast<int*>(bufptr);
  21. *len = size;
  22. bufcount += sizeof(int);
  23. bufptr += sizeof(int);
  24. void *ptr = reinterpret_cast<void*>(bufptr);
  25. bufptr += size;
  26. bufcount += bufcount;
  27. cout << "alloc: " << (size + sizeof(int)) << endl;
  28. cout << "free: " << (BUFSIZE - (bufptr - buf)) << endl;
  29. return ptr;
  30. }
  31.  
  32. }
  33.  
  34. void* operator new (size_t t) { return foo::getnewbuf((int)t); }
  35. void operator delete (void* p) { cout << "delete" << endl; }
  36.  
  37. struct Bar
  38. {
  39. static int cnt;
  40. int zero[100];
  41. int id;
  42. Bar() : id(cnt++) { cout << "Bar(): " << id << endl; }
  43. ~Bar() { cout << "~Bar(): " << id << endl; }
  44. };
  45. int Bar::cnt = 0;
  46.  
  47. int main() {
  48. // your code goes here
  49.  
  50. int *p = new int;
  51.  
  52. delete p;
  53.  
  54. Bar *bar = new Bar;
  55.  
  56. delete bar;
  57.  
  58. try {
  59. Bar bbb;
  60. auto_ptr<Bar> aaa(new Bar);
  61. bar = new Bar[100];
  62.  
  63. delete [] bar;
  64. }
  65. catch (bad_alloc& e) {
  66. cout << e.what() << endl;
  67. }
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 3440KB
stdin
Standard input is empty
stdout
alloc: 8
free: 9992
delete
alloc: 408
free: 9584
Bar(): 0
~Bar(): 0
delete
Bar(): 1
alloc: 408
free: 9176
Bar(): 2
~Bar(): 2
delete
~Bar(): 1
std::bad_alloc