Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free C-malloc()'d memory in Swift?

I'm using the Swift compiler's Bridging Header feature to call a C function that allocates memory using malloc(). It then returns a pointer to that memory. The function prototype is something like:

char *the_function(const char *);

In Swift, I use it like this:

var ret = the_function(("something" as NSString).UTF8String)

let val = String.fromCString(ret)!

Forgive my ignorance concerning Swift but normally in C, if the_function() is malloc'ing memory and returning it, somebody else needs to free() it at some point.

Is this being handled by Swift somehow or am I leaking memory in this example?

Thanks in advance.

like image 529
Christopher Avatar asked Jun 24 '15 07:06

Christopher


1 Answers

Swift does not manage memory that is allocated with malloc(), you have to free the memory eventually:

let ret = the_function("something") // returns pointer to malloc'ed memory
let str = String.fromCString(ret)!  // creates Swift String by *copying* the data
free(ret) // releases the memory

println(str) // `str` is still valid (managed by Swift)

Note that a Swift String is automatically converted to a UTF-8 string when passed to a C function taking a const char * parameter as described in String value to UnsafePointer<UInt8> function parameter behavior. That's why

let ret = the_function(("something" as NSString).UTF8String)

can be simplified to

let ret = the_function("something")
like image 180
Martin R Avatar answered Oct 07 '22 10:10

Martin R