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