[swift-users] UnsafeMutablePointer on the stack?

Jean-Denis Muys jdmuys at gmail.com
Sun Oct 2 18:15:07 CDT 2016


Hi,

I have some issues using the new raw memory API. For instance, let's
suppose I want to call the `SecRandomCopyBytes` API to generate a
cryptographically secure random 32-bit number. The difficulty is its 3rd
argument, which is declared as UnsafeMutablePointer<UInt8>. Here is a
function that does that:

func entropicRandom() -> UInt32 {

    let randomWordPT = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)


    let _ = randomWordPT.withMemoryRebound(to: UInt8.self, capacity: 4) {
(p: UnsafeMutablePointer<UInt8>) -> Int32 in

        let result = SecRandomCopyBytes(kSecRandomDefault, MemoryLayout<
UInt32>.size, p)

        return result

    }

    let randomInt32 = randomWordPT[0]

    randomWordPT.deallocate(capacity: 1)

    return randomInt32

}

apparently, the calls to allocate and then deallocate suggest that there is
some heap allocation happening behind the scene here, possibly malloc/free.
Is that correct?

If so, this is quite wasteful. Is there a way to use a local variable on
the stack to achieve the same result?

Thanks,

Jean-Denis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161003/c5a3cbda/attachment.html>


More information about the swift-users mailing list