Nathan P
Nathan P

Reputation: 1006

Aligned memory in Swift 3

In previous versions of Swift, I have been able to use the posix_memalign function to allocate aligned memory to help optimize certain operations. Since upgrading to the Swift 3 beta (packed with Xcode 8 beta 2), it has been failing and I am not sure why. It could simply be an issue with the beta, or maybe I simply need to change how I am interface with the function.

The sample code that I have been using for investigating the issue is shown below. (It tries to allocate a buffer of floating point numbers that is 16K aligned.)

var pointer: UnsafeMutablePointer<Void>? = nil
let alignment: Int = 0x4
let length: Int = bufferSize

let ret = posix_memalign(&pointer, alignment, length * sizeof(Float))

if ret != noErr {
    let err = String(validatingUTF8: strerror(ret)) ?? "unknown error"
    fatalError("Unable to allocate aligned memory: \(err).")
}

The posix_memalign fails with an "Invalid argument." message.

Any ideas?

Upvotes: 1

Views: 670

Answers (1)

Nathan P
Nathan P

Reputation: 1006

I realized that my alignment was not a multiple of 8, but instead a multiple of 4, which is an invalid alignment (posix_memalign expects alignments to be a multiple of a the length of a UnsafeMutablePointer<Void>).

Simply correcting my alignment fixed the issue.

More surprisingly, the code did work in Swift 2, but has stopped working in Swift 3 (the beta included with Xcode 8). The only related change has been the switch from allowing UnsafeMutablePointer to be nil in the previous version, while it now must be optional to reflect the fact that it can be nil.

Upvotes: 1

Related Questions