Open
Description
Description
I have a C-style Swift function that will be called from C++ later. This is my "callback":
func callCppCode() {
func __callback(value: SharedPtrOfString) {
let string = String(value.pointee)
print("Got value from C++: \(value)")
}
myCppFunc(__callback)
}
And on the C++ side, myCppFunc
looks like this:
#pragma once
#include <string>
#include <memory>
using SharedPtrOfString = std::shared_ptr<std::string>;
inline void myCppFunc(void(* _Nonnull call)(SharedPtrOfString)) {
auto shared = std::make_shared<std::string>("HELLO!");
call(shared);
}
When running this, it crashes with the following error:
- SwiftSharedPointerTest(33577,0x1e6e6f840) malloc: Heap corruption detected, free list is damaged at 0x600002b91a10
- *** Incorrect guard value: 1
- SwiftSharedPointerTest(33577,0x1e6e6f840) malloc: *** set a breakpoint in malloc_error_break to debug
Note
When I replaced SharedPtrOfString
with Double
or even std.string
, it works. It's just std::shared_ptr<...>
that makes it crash with a heap corruption error.
Reproduction
func callCppCode() {
func __callback(value: SharedPtrOfString) {
let string = String(value.pointee)
print("Got value from C++: \(value)")
}
myCppFunc(__callback)
}
#pragma once
#include <string>
#include <memory>
using SharedPtrOfString = std::shared_ptr<std::string>;
inline void myCppFunc(void(* _Nonnull call)(SharedPtrOfString)) {
auto shared = std::make_shared<std::string>("HELLO!");
call(shared);
}
Stack dump
Got value from C++: shared_ptr<basic_string<CChar, char_traits<CChar>, allocator<CChar>>>()
SwiftSharedPointerTest(34066,0x1e6e6f840) malloc: Heap corruption detected, free list is damaged at 0x600001726730
*** Incorrect guard value: 7813868916180873059
SwiftSharedPointerTest(34066,0x1e6e6f840) malloc: *** set a breakpoint in malloc_error_break to debug
Expected behavior
I expect the shared_ptr
to be free'd fine instead of corrupting the heap.
Environment
swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Target: arm64-apple-macosx15.0
Additional information
I have created a reproduction repro here: https://github.com/mrousavy/SwiftSharedPointerBugRepro
Just download and run this (I chose "Run on my Mac (Designed for iPad)") to see the bug.