Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

392
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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")
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!