Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

395
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda