Free C-malloc () 'memory in Swift?

I use the Swift compiler function to call the C function, which allocates memory using malloc() . Then it returns a pointer to this memory. The prototype of the function is something like:

 char *the_function(const char *); 

In Swift, I use it as follows:

 var ret = the_function(("something" as NSString).UTF8String) let val = String.fromCString(ret)! 

Forgive my ignorance regarding Swift, but usually in C, if the_function () is a malloc'ing memory and returns it, someone else needs to free () at some point.

Is this in some way processed by Swift or will I skip memory in this example?

Thanks in advance.

+5
source share
1 answer

Swift does not manage the memory allocated with malloc() , you should end up freeing the memory:

 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 the Swift String automatically converted to a UTF-8 string when passing the C function with the const char * parameter as described in the String value for 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") 
+5
source

All Articles