Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle UnsafeMutablePointer correctly

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 freeis 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?

like image 871
enovatia Avatar asked Jul 04 '16 01:07

enovatia


1 Answers

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".)

like image 103
OOPer Avatar answered Oct 02 '22 16:10

OOPer