Skip to content

C++ interop crash adding Strings of > 15 bytes to Swift Array. #69372

@efroemling

Description

@efroemling

Description
When creating a Swift Array of Strings from C++ code (as described in the guide), adding strings with a size greater than 15 bytes causes a crash.

Steps to reproduce
The following steps reproduce the crash for me using XCode 15.0.1 (15A507) on an M1 Max MBP running Sonoma 14.1:

  • Create a new ‘Command Line Tool’ project named “TestCommand”.
  • Create a new C++ file named ‘test’ (with header). Click ‘Create Bridging Header’ when it asks.
  • In TestCommand-Bridging-Header.h, add:
    #include "test.hpp"
  • In test.hpp, add:
    void doTest();
  • In test.cpp, add:
    #include <TestCommand-Swift.h>
    
    void doTest() {
      // Pass an array back to our Swift code to print.
      auto array = swift::Array<swift::String>::init();
      array.append("foo");
      TestCommand::printStrings(array);
    }
  • In main.swift, add:
    // Expose a print call for C++ to use.
    public func printStrings(_ strings: [String]) {
      for s in strings {
        print("GOT STRING", s)
      }
      print("DONE PRINTING.")
    }
    
    // Call our c++ code.
    doTest()
  • Under build settings for the TestCommand target, set C++ and Objective-C Interoperability to “C++/Objective C++”
  • You should now be able to build and run the project, which should give the following output:
    Hello, World!
    GOT STRING foo
    DONE PRINTING.
    Program ended with exit code: 0
    
  • Now, to trigger the crash, simply change the "foo" in test.cpp to "123456789ABCDEFG" and run again. You should see the following output followed by an EXC_BAD_ACCESS crash at the end of the doTest function.
    Hello, World!
    GOT STRING ����������������
    DONE PRINTING.
    <crashes here in swift::Array<swift::String>::~Array()>
    

As per the discussion of this crash on the swift forums, it appears that the threshold for causing a crash is strings > 15 characters which corresponds to String's inline storage size.

Environment

  • Swift compiler version info: swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)

  • Xcode version info: Xcode 15.0.1 Build version 15A507

  • Deployment target: macOS Sonoma 14.1 (23B73)

Metadata

Metadata

Assignees

Labels

ArrayArea → standard library: The `Array` typebugA deviation from expected or documented behavior. Also: expected but undesirable behavior.c++ interopFeature: Interoperability with C++compilerThe Swift compiler itselfcrashBug: A crash, i.e., an abnormal termination of softwareownershipFeature: Ownership modifiers and semanticsswift 5.10swift to c++Feature → c++ interop: swift to c++

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions