0

So I tried running our app with "Address Sanitizer" enabled. And I got this crash:

let sData = "-e5069fba-3612".data(using:String.Encoding.utf8)!
var pointer = sData.withUnsafeBytes {(bytes: UnsafePointer<CChar>) -> UnsafePointer<CChar> in
    return bytes
}
pointer = pointer.advanced(by: 1)
let tmpPIN = String(cString: pointer)
print(tmpPIN)

the crash points to let tmpPIN = String(cString: pointer). Does anyone know the reason behind this? I can't figure out why this is happening.

Note, the app runs fine when I disabled the "Address Sanitizer". Should I be worry about this or just ignore it?

SquareBox
  • 823
  • 1
  • 10
  • 22
  • The more interesting question to me is why you're converting from a `String` to UTF8, getting unsafe bytes, and using a C-style string initializer when you want to end up with another `String` at the end. Is this intended to just strip the `-` from the beginning? – Tom Harrington Mar 28 '18 at 15:06
  • @TomHarrington thanks for this! The first line actually is not the exact code from our app. I created a dummy app base on our code just to replicate the said error and I need dummy `Data` so I create one with the said `String`. I can't post our exact codes for privacy reasons. – SquareBox Apr 03 '18 at 00:01

2 Answers2

2

It seems you found an answer that works, but I'm adding one because I'm still kind of baffled by such complex code for such a simple problem.

Your code:

  • Transforms a Swift string to a Data object,
  • Gets unsafe bytes from that
  • Does pointer math on the unsafe bytes to move ahead one byte,
  • Finally converts the result back into a String.

Your fix makes it even more complex by appending an extra byte you don't even want (it works because C strings are expected to have a null character at the end, and your fix adds that).

This could be done far more simply as:

let sData = "-e5069fba-3612"
let tmpPIN = sData2.dropFirst()

The result is exactly the same.

Or you could handle multiple - characters at the start with something like

let tmpPIN = sData.drop { $0 == "-" }

Which gives the same result for this string.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
0

I found this thread... When I add sData.append(0) after I initialize the sData the Address Sanitizer error is gone.

SquareBox
  • 823
  • 1
  • 10
  • 22