Skip to content

Instantly share code, notes, and snippets.

@voidbar
Created June 26, 2022 10:23
Show Gist options
  • Select an option

  • Save voidbar/00287bc1c231bba7c1131eebb52c0765 to your computer and use it in GitHub Desktop.

Select an option

Save voidbar/00287bc1c231bba7c1131eebb52c0765 to your computer and use it in GitHub Desktop.
C++ Spot the Bug
template <typename Func>
auto decorator(Func func) {
return [&]{
std::cout << "Calling f():\n";
func();
};
}
auto foo(fs::path filepath) {
auto func = [filepath] {
std::cout << filepath << "\n";
});
auto newfunc = decorator(func);
return newfunc;
}
int main(){
auto newfunc = foo(fs::path("C:\\"));
newfunc();
}
/*
Can you spot the bug?
filepath is being captured by copy into the func lambda,
basically creating a member variable for it.
Then, we passfunc to the function decorator and return a new lambda that invokes func.
The decorator's lambda know which func to call only by reference (capturing [&]) - but alas,
when invoking newfunc in main, func has already been freed due to RAII!
So undefined behavior would occur trying to access uninitialized address.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment