Correct way to call “realloc” in Swift with a Floa

2019-04-01 01:34发布

问题:

I'm trying figure out what size to send "realloc" when I call it through Swift. It seems that I have to add an extra byte, but I don't understand why.

typealias Floats = UnsafeMutablePointer<Float>

let FLOAT_SIZE = sizeof( Float )

func floats_realloc( floats:Floats, qty_of_floats:Int ) -> Floats  {

     let KLUDGE = 1 // Why?

     let qty_of_bytes = ( qty_of_floats * FLOAT_SIZE ) + KLUDGE

     let realloced_floats = Floats(

          realloc( floats, UInt( qty_of_bytes ) )

     )

     return realloced_floats

}

If I set KLUDGE to 0 here, this is what happens when I attempt to make room for one new member in a three member array:

In: [0.9, 0.9, 0.9]

Out: [0.0, 0.0, 0.9, 0.0]

What I would expect is:

Out: [0.9, 0.9, 0.9, 0.0]

The arrays I'm sending it are created within Swift, using

var foo_floats = Floats.alloc(QTY_OF_FLOATS)

What's wrong with my call to realloc?

回答1:

I've discussed this on Apple's Developer Forum. It turns out that using Swift's alloc allots space for a Swift array, not a C array. So if you want to use MutableUnsafePointer for a C array and "realloc" (bridged from C) you need to stick with C functions, like "malloc" (bridged from C).

By adding the following function, and using it when I initially set up my Floats array, the "realloc" bug went away:

func floats_alloc( qty_of_floats:Int ) -> Floats  {

      // return Floats.alloc( qty_of_floats )

      let qty_of_bytes = ( qty_of_floats * FLOAT_SIZE )

      let alloced_floats = Floats(

           malloc( UInt( qty_of_bytes ) )

      )

      return alloced_floats

 }

I've tested for a couple weeks now, and all is well.



标签: swift realloc