Issue 172162
Summary [clang-cl/Windows] Runtime crash/stack corruption when passing captureless lambda directly to C function pointer
Labels new issue
Assignees
Reporter LearnerJhz
    ### Summary
I encountered a runtime crash (likely stack corruption) when compiling C++ code with Clang on Windows. The issue occurs when passing a **captureless lambda** directly as an argument to a C library function that expects a function pointer.

The same code works perfectly when compiled with **MSVC**.
Interestingly, the crash disappears if I assign the lambda to a variable (e.g., `auto` or explicit function pointer type) before passing it to the function.

### Environment
- **OS**: Windows 10 (x64)
- **Compiler**: Clang version 21.1.6
- **Target**: x86_64-pc-windows-msvc
- **Build System**: CMake + Ninja

### Steps to Reproduce
1. Define a C-style callback type (or use a library like miniaudio).
2. Create a function that accepts this function pointer.
3. Pass a captureless lambda **directly** to this function.
4. Run the compiled executable.

### Minimal Reproducible Example
However, this particular case was successful. To be honest, the issue I encountered was far more complicated—almost like a Heisenbug—and it is difficult to reliably reproduce.
```
#include <iostream>

// Mocking the C library definition (e.g. miniaudio style)
// Usually implies __cdecl on Windows for C libs
typedef int (*CallbackProc)(void* pUserData);

void library_init_function(CallbackProc proc, void* pUserData) {
    // Calling the callback
    int result = proc(pUserData); 
    std::cout << "Callback returned: " << result << std::endl;
}

int main() {
    // This CRASHES or causes stack corruption with Clang:
    library_init_function([](void* pUserData) -> int {
        return 0;
    }, nullptr);

    // This WORKS with Clang:
    // auto func_ptr = [](void* pUserData) -> int { return 0; };
    // library_init_function(func_ptr, nullptr);

    return 0;
}
```
Expected Behavior
The program should run successfully and the callback should be invoked correctly, just like in MSVC.

Actual Behavior
The program crashes at runtime, specifically when the callback returns or when the host function tries to continue execution. This suggests a calling convention mismatch (e.g., the compiler might be generating a wrapper with the wrong stack cleanup logic for the lambda-to-pointer conversion).

Additional Context
It seems to be an issue with how Clang handles the implicit conversion decay of the lambda object to a function pointer in a temporary context on Windows.

Workaround: Assigning the lambda to an lvalue (variable) or using a static member function solves the issue.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to