fork download
  1. #include <iostream>
  2.  
  3. class DangerousString {
  4. private:
  5. std::string data;
  6. public:
  7. DangerousString(const std::string& str) : data(str) {
  8. std::cout << "DangerousString created: " << data << std::endl;
  9. }
  10.  
  11. ~DangerousString() {
  12. data = "";
  13. std::cout << "DangerousString destroyed: " << data << std::endl;
  14. }
  15.  
  16. const char* getCStr() const {
  17. return data.c_str();
  18. }
  19. };
  20.  
  21. void log(const char* str) {
  22. std::cout << "Log message: " << str << std::endl;
  23. }
  24.  
  25. int main() {
  26. const char* danglingPtr = DangerousString("Hello, World!").getCStr(); // ❌ UB!
  27. std::cout << "Before log call" << std::endl;
  28. log(danglingPtr); // Висячий указатель передаётся в log()!
  29. }
  30.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
DangerousString created: Hello, World!
DangerousString destroyed: 
Before log call
Log message: