5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Christopher
  • 1,635
  • 5
  • 19
  • 30

1 Answers1

8

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")
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks for the code snippet! While it seems simple and obvious, I had no idea on how to do it at first because I wasn't aware that Swift `String` initializer **copy** the C buffer. Even the example code in the [Apple doc](https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/using_imported_c_functions_in_swift) forgot to call `free()`. – rayx Jun 07 '21 at 12:11