Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn about static lambda capturing local variable by reference #111316

Open
HighCommander4 opened this issue Oct 6, 2024 · 1 comment
Open

Warn about static lambda capturing local variable by reference #111316

HighCommander4 opened this issue Oct 6, 2024 · 1 comment
Labels
clang:diagnostics New/improved warning or error message in Clang, but not in clang-tidy or static analyzer

Comments

@HighCommander4
Copy link
Collaborator

Capturing a local variable by reference in a static lambda is a recipe for undefined behaviour:

int foo() {
  int result = 0;
  static auto lambda = [&result] {
    ++result;
  };
  lambda();
  return result;
}

int main() {
  foo();
  foo();  // oops, the lambda is modifying the `result` variable from the first call
}

It would be nice if clang warned about this.

(Such a bug was caught recently in the LLVM codebase itself, #109367.)

@HighCommander4 HighCommander4 added the clang:diagnostics New/improved warning or error message in Clang, but not in clang-tidy or static analyzer label Oct 6, 2024
@shafik
Copy link
Collaborator

shafik commented Oct 7, 2024

Note asan does catch this: https://godbolt.org/z/ahGY31f6r

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:diagnostics New/improved warning or error message in Clang, but not in clang-tidy or static analyzer
Projects
None yet
Development

No branches or pull requests

2 participants