I am trying to convert the following ObjC code to Swift and found it not as easy due to memory leak. num_threads_objc() below works fine while num_threads_swift() below seems leaking memory according to Xcode. I suspect the use of vm_deallocate() below is wrong, but can't figure out how.
What am I missing?
threads! is the pointer to the memory to be freed (as @jrose said), but vm_deallocate expects the address as an vm_address_t aka UInt. In (Objective-)C you can simply cast the pointer to an
integer. In Swift you need the init(bitPattern:) initializer.
I have a question,both MemoryLayout<thread_t>.size, MemoryLayout<thread_t>.stride and sizeof(thread_t) have a value of 4, but MemoryLayout.stride and sizeof use memory alignment, so I think using MemoryLayout.stride is more accurate. This is my personal idea, can anyone explain it to me.
If so, then yeah, using stride is probably the most correct option. However, in this case thread_t is a UInt32 [1], so it doesn’t matter. Moreover, I don’t think it will ever matter when dealing with basic Mach types like this because they never have any padding.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
[1] Via the chain thread_t > mach_port_t > __darwin_mach_port_t is __darwin_mach_port_name_t > __darwin_natural_t > UInt32, which is quite a chain!