Search code examples
swiftmemory-managementmallocsizeofmemory-layout

Why Swift's malloc/MemoryLayout.size take/return signed integers?


public func malloc(_ __size: Int) -> UnsafeMutableRawPointer!

@frozen public enum MemoryLayout<T> {
    public static func size(ofValue value: T) -> Int
    ...

When in C malloc/sizeof take/return size_t which is unsigned? Isn't Swift calling libc under the hood?

EDIT: is this the reason why? https://qr.ae/pvFOQ6 They are basically trying to get away from C's legacy?


Solution

  • Yes, it's calling the libc functions under the hood.

    The StdlibRationales.rst document in the Swift repo explains why it imports size_t as Int:

    Converging APIs to use Int as the default integer type allows users to write fewer explicit type conversions.

    Importing size_t as a signed Int type would not be a problem for 64-bit platforms. The only concern is about 32-bit platforms, and only about operating on array-like data structures that span more than half of the address space. Even today, in 2015, there are enough 32-bit platforms that are still interesting, and x32 ABIs for 64-bit CPUs are also important. We agree that 32-bit platforms are important, but the usecase for an unsigned size_t on 32-bit platforms is pretty marginal, and for code that nevertheless needs to do that there is always the option of doing a bitcast to UInt or using C.