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

389
Views
¿Memoria C-malloc() libre en Swift?

Estoy usando la función Bridging Header del compilador Swift para llamar a una función C que asigna memoria usando malloc() . Luego devuelve un puntero a esa memoria. El prototipo de función es algo así como:

 char *the_function(const char *);

En Swift, lo uso así:

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

Perdone mi ignorancia con respecto a Swift, pero normalmente en C, si the_function() está almacenando memoria y devolviéndola, alguien más necesita liberarla() en algún momento.

¿Swift está manejando esto de alguna manera o estoy perdiendo memoria en este ejemplo?

Gracias por adelantado.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Swift no administra la memoria asignada con malloc() , eventualmente debe liberar la memoria:

 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)

Tenga en cuenta que una String Swift se convierte automáticamente en una cadena UTF-8 cuando se pasa a una función C que toma un parámetro const char * como se describe en Valor de cadena para el comportamiento del parámetro de función UnsafePointer<UInt8> . Es por eso

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

se puede simplificar a

 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!