[swift-users] How much memory does withMemoryRebound bind

Etan Kissling etan at scriptreactor.com
Thu Dec 29 07:27:01 CST 2016


Hi,

When calling POSIX accept, the common way is to
sockaddr_storage addr = {0};
sockaddr_len addrlen = 0;
int clientFd = accept(serverFd, (sockaddr *) &addr, &addrlen);

In Swift, this translates to
var addr = sockaddr_storage()
var addrlen = sockaddr_len(0)
int clientFd = withUnsafeMutablePointer(to: addr) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { addr in
        Foundation.accept(socket, addr, &addrlen)
    }
}

Since sockaddr is smaller than sockaddr_storage, I wonder if this is correct.

If withMemoryRebound would be the same as the simple C cast, it would be okay.
However, since it also requires passing the capacity, I wonder if there may be cases
where it actually copies out the memory region, which could lead to memory corruption.

==> How can I guarantee that withMemoryRebound binds the complete sockaddr_storage,
       and prevent cases where only the first MemoryLayout<sockaddr>.size bytes are bound?

Thanks

Etan


More information about the swift-users mailing list