fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. struct Yoo
  6. {
  7. Yoo(const char* s) : str(new std::string(s)) {}
  8. ~Yoo() { delete str; str = nullptr; }
  9. std::string* str;
  10. };
  11.  
  12. const size_t K = 1024;
  13. const size_t SZ = 16 * K; // some big size
  14.  
  15. struct YooDeleter
  16. {
  17. void operator()(Yoo* p) { delete p; }
  18. char dummy[SZ]; // make the deleter big
  19. };
  20.  
  21. void bar()
  22. {
  23. std::shared_ptr<Yoo> sp;
  24.  
  25. Yoo* p = new Yoo("Hello");
  26.  
  27. // try to exhaust heap memory.
  28. std::vector<std::unique_ptr<YooDeleter>> holder;
  29. holder.reserve(2048 * K); // 2M entries, big enough
  30. for (;;)
  31. {
  32. try
  33. {
  34. std::unique_ptr<YooDeleter> p(new YooDeleter);
  35. holder.push_back(std::move(p));
  36. }
  37. catch (...)
  38. {
  39. break;
  40. }
  41. }
  42. std::cout << "Heap used: " << holder.size() << " x " << SZ / K << "KB" << std::endl;
  43.  
  44. try
  45. {
  46. YooDeleter x;
  47. std::cout << "Creating shared_ptr..." << std::endl;
  48. sp = std::shared_ptr<Yoo>(p, x);
  49. }
  50. catch (std::bad_alloc& e)
  51. {
  52. // cannot construct sp: out of memory
  53. std::cout << "Out of memory..." << std::endl;
  54. std::cout << "I am about to crash..." << std::endl;
  55. std::cout << p->str->c_str() << std::endl; // undefined behavior, mostly crash
  56. delete p; // will not even arriving here!
  57. return;
  58. }
  59. catch(...)
  60. {
  61. std::cout << "Unknown error..." << std::endl;
  62. return;
  63. }
  64.  
  65. // it will never be here!
  66. *sp->str = "Bye";
  67. std::cout << sp->str->c_str() << std::endl; // "Bye"
  68. }
  69.  
  70. int main()
  71. {
  72. bar();
  73. return 0;
  74. }
Runtime error #stdin #stdout 0.15s 1043456KB
stdin
Standard input is empty
stdout
Heap used: 64457 x 16KB
Creating shared_ptr...
Out of memory...
I am about to crash...