[swift-users] How much memory does withMemoryRebound bind

Etan Kissling etan at scriptreactor.com
Thu Dec 29 08:52:06 CST 2016


I meant the question in a more generalized sense. 
The sockaddr example is just one that is easily understandable :-)

Thanks for the link though, interesting read!

> On 29 Dec 2016, at 14:47, Rien <Rien at Balancingrock.nl> wrote:
> 
> I used the code from http://blog.obdev.at/representing-socket-addresses-in-swift-using-enums/ in my package SwifterSockets (see github link below)
> 
> It does not answer your question exactly, but I think it is a rather better approach to sockaddr usage.
> 
> Regards,
> Rien
> 
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Swiftrien
> Project: http://swiftfire.nl
> 
> 
> 
> 
>> On 29 Dec 2016, at 14:27, Etan Kissling via swift-users <swift-users at swift.org> wrote:
>> 
>> 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
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 



More information about the swift-users mailing list