Created
June 26, 2022 10:23
-
-
Save voidbar/00287bc1c231bba7c1131eebb52c0765 to your computer and use it in GitHub Desktop.
C++ Spot the Bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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