I am a little confused. When do I have to call free and when destroy/dealloc? I am working on a short code snippet learning core audio. I thought if I call UnsafeMutablePointer<Type>.alloc(size)
then I should call destroy
& dealloc
.
But if I use malloc()
or calloc()
I am supposed to call free()
.
In this example from Learning Core Audio the following code snippet makes me wonder:
var asbds = UnsafeMutablePointer<AudioStreamBasicDescription>.alloc(Int(infoSize))
audioErr = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(sizeof(fileTypeAndFormat.dynamicType)), &fileTypeAndFormat,
&infoSize, asbds)
Here I use alloc
. To free up memory free
is called.
free(asbds)
But why not
asbds.destroy(Int(infoSize))
asbds.dealloc(Int(infoSize))
which I would expect following the rule.
I would appreciate any help, because this makes my head spin. The documentation says I am responsible for destroying and dealloc so that part is clear, but in which way?
See the UnsafeMutablePointer Structure Reference.
The pointer can be in one of the following states:
Memory is not allocated (for example, pointer is null, or memory has been deallocated previously).
Memory is allocated, but value has not been initialized.
Memory is allocated and value is initialized.
You can use the pointed region safely when "allocated and initialized".
So, if you want to use Swift's UnsafeMutablePointer
correctly, you need 2 steps before using and 2 steps after using.
(1) Allocate: alloc(_:)
.
(2) Initilize: initialize...()
You can safely use the allocated and initialized region here.
(3) Deinitialize: destroy(_:)
(4) Deallocate: dealloc(_:)
And why you can use free()
for alloc(_:)
ed memory, that's because Swift uses malloc(_:)
in the current implementation of alloc(_:)
. So, using free means that your app depends on the current implementation of the Swift runtime.
So, using UnsafeMutablePointer
is sort of difficult and annoying. You should consider passing an array as a pointer.
In your case, you can write something like this:
let elementCount = Int(infoSize) / strideof(AudioStreamBasicDescription)
var asbds: [AudioStreamBasicDescription] = Array(count: elementCount, repeatedValue: AudioStreamBasicDescription())
audioErr = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
UInt32(sizeof(fileTypeAndFormat.dynamicType)), &fileTypeAndFormat,
&infoSize, &asbds)
(I think you should use this elementCount
even when using UnsafeMutablePointer
. alloc(_:)
or dealloc(_:)
uses "number of elements", not "byte size".)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With