Won't extend it one more time!

C++ On Sea 2022, ⚡ Lightning talks ⚡
Sandor Dargo

We had to ship something "bugfree"

  • One of the first adopters experiences a regression
  • Only one of them
  • Only on one of their servers

The disturbance in the force

  • Non-determenistic error codes from our 3rd party service
  • Though it started around the load
  • Restarting the 3rd party server helped
  • All our tests are fine both with old/new versions
  • Reading the code for a long time, but finding nothing

Don't believe in coincidences!

  • I simplify the critical path as much as meaningful
  • Couldn't trigger any warning

  • I want to get more familiar with clang tools...
  • UB Sanitizer, Memory Sanitizer and found nothing
  • Finally, the Address Sanitizer found an error!

ERROR: stack-use-after-scope

class Parameters {
public:
    // ...
    boost::variant<VariantA, VariantB> get() const {return params;}
private:
    boost::variant<VariantA, VariantB> params;
};

void foo(const Parameters& p) {
     const auto& va = boost::get<VariantA>(p.get());
     bar((unsigned char*)va.url.c_str());
}

void bar(unsigned char * data) { /* ... */ }

Went through the 5 steps of grief!

  • Denial: it cannot be that, the lifetime is extended!
  • Anger: stupid me, this line was already suspicious!
  • Bargaining: what if I paid more attention... what if other paid more attention?
  • Depression: I still think it's impossible, what the heck?
  • Acceptance: OK, it's that. I must understand and learn from it!

Then it hit me!

<< In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime. >> - cppreference.com - Reference initialization

First, then second

const auto& va = 
    boost::get<VariantA>( // no second extension...
      p.get() // first extension
    );


Be paranoid!

Don't introduce lifetime extension!

Remove it when possible!

Won't extend it one more time!

C++ On Sea 2022, ⚡ Lightning talks ⚡
Sandor Dargo

<style scoped> section { color: yellow; } </style>

# The context of our bughunt * We must ship on time! * We must ship once! * We cannot afford a bugfix! <br/> * We work... * And work... * And ship on time! ---

<style scoped> section { color: yellow; } </style>