Talk about unsafe c

Asked on 06/16/2025

1 search

At WWDC 2025, Apple introduced several features and tools to enhance the safety of using C and C++ with Swift, particularly focusing on addressing the challenges of unsafe constructs in C and C++.

Key Points on Unsafe C and C++:

  1. Unsafe Pointers: C and C++ pointers are inherently unsafe because they can lead to security and stability issues like buffer overflows and use-after-free errors. Swift imports these pointers as unsafe types, such as UnsafeMutablePointer, to signal the lack of safety guarantees.

  2. Strict Memory Safety: Swift 6.2 introduces a new compiler mode called Strict Memory Safety. This mode alerts developers to any unsafe code and provides notes explaining the reasoning. It is not enabled by default but can be turned on in Xcode to help identify and address unsafe constructs (Safely mix C, C++, and Swift).

  3. Annotations for Safety: Developers can add annotations to C and C++ code to convey missing information, allowing Swift to call these functions safely. This includes annotating functions to express bounds and lifetime information, which helps Swift treat unsafe pointers as safe spans (Safely mix C, C++, and Swift).

  4. Bound Safety Tools: Apple has developed tools to enhance bound safety in C and C++. These tools include enabling bound safety checks in Xcode and using language extensions to ensure bounds are respected in C code (Safely mix C, C++, and Swift).

  5. Swift Spans: Swift introduces a new type called Span, which acts like a pointer but with built-in safety features. This type helps prevent common pointer-related mistakes, such as out-of-bounds access (Safely mix C, C++, and Swift).

These efforts are part of Apple's ongoing work to make C and C++ code safer when used in conjunction with Swift, acknowledging that while C and C++ can never be as safe as Swift, they can be made safer with the right tools and practices.