4

I am allocating bytes using the following call in Swift 3:

let wordSize = 2
let numbytes = 1024*wordsize
var ptr = UnsafeMutableRawPointer.allocate(bytes: numbytes, alignedTo: wordSize)

Question is whether it is correct to deallocate the memory, are both these calls one and the same, or I should be using one over the other?

  free(ptr) // opt 1

  ptr.deallocate(bytes: numbytes, alignedTo: wordSize) //opt 2
Hamish
  • 78,605
  • 19
  • 187
  • 280
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • 1
    Compare [How to handle UnsafeMutablePointer correctly](http://stackoverflow.com/q/38175870/2976878). You should use `deallocate` – `free` may work, but that relies on an implementation detail of the Swift runtime. – Hamish May 01 '17 at 11:03
  • I have edited out the [swift3] tag (again) – as it is only for questions *directly* related to changes in the language for that version, which yours is not. This is evident by the fact that it is (more or less) answered by the above linked Q&A, which was for Swift 2. – Hamish May 01 '17 at 15:56
  • @Hamish this question uses Swift 3 syntax. As I noted in my answer, there is an appropriate answer in Swift 4 with different syntax. Does that affect your decision to remove the language version from the tags? I'm just curious; I really don't care what this question is tagged – Ky - Feb 01 '19 at 22:38
  • 1
    @BenLeggiero The version specific tags are only meant to be used for questions specifically about changes in the language for that particular version (as stated in their tag wikis), not just questions about code using that version. I used to edit quite a lot of questions to remove incorrectly used version tags, but ultimately gave up as they're too frequently misused. – Hamish Feb 01 '19 at 22:54

1 Answers1

4

Swift 4 changed this signature to deallocate(), making it much easier to decide when compared to free(_:).

As Hamish pointed out, deallocate is the preferred way to deallocate unsafe pointers in Swift, a fact which is reinforced by the API designers placing this function on the type and documenting it, whereas free(_:) is global-scope (rarely appropriate in Swift) and undocumented.

Ky -
  • 30,724
  • 51
  • 192
  • 308