Trikalabs
  • Home
  • Best online TDD videos
  • Book Suggestions
  • About Me
  • Contact
Trikalabs
No Result
View All Result

How to handle UnsafeMutablePointer in Swift

by fragi
February 21, 2022
in Memory Management
Share on FacebookShare on Twitter

value e thetedmorey we allocatedHandling UnsafeMutablePointers can be tricky because if it is not done right can leave dangling pointers.

Let’s for example the following method:

The method expects two dangling pointers as arguments.

In order to be on the safe side we have first to initialise and allocate the space to our two variables:

Swift
1
2
3
        let capacity = 32
        let pk = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)
        let sk = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)

The next step is to make sure we place the right input data to these variables:

Swift
1
2
3
4
        for i in 0..<capacity {
            (pk + i).initialize(to: 0)
            (sk + i).initialize(to: input[i])
        }

Now we pass these variables in our method call:

Swift
1
modified_crypto_sign_publickey(pk, sk)

Now we must deallocate the memory we allocated but before we do that lets save to another variable the variable:

Swift
1
2
3
4
        var pkCopy: [UInt8] = Array(repeating: 0, count: capacity)
        for i in 0..<capacity {
            pkCopy[i] = (pk + i).pointee
        }

And lastly we deallocate the memory:

Swift
1
2
        pk.deallocate()
        sk.deallocate()

There are two WWDC videos regarding Unsafe Swift:
https://developer.apple.com/videos/play/wwdc2020/10648/
https://developer.apple.com/videos/play/wwdc2020/10167/

fragi

fragi

Related Posts

No Content Available
Next Post
Performance testing in Xcode

Performance testing in Xcode

Memoization

Memoization

Detect unused code – Periphery

Detect unused code - Periphery

  • Advertise
  • Privacy & Policy
  • Contact

© 2019 Trikalabs Ltd. All rights reserved.

No Result
View All Result
  • Home
  • About Me
  • A curated list with the best free online TDD videos
  • Book Suggestions
  • Pinner Code Club

© 2019 Trikalabs Ltd. All rights reserved.