2

My code, which use SimplePing:

func simplePing(_ pinger: SimplePing, didSendPacket packet: Data, sequenceNumber: UInt16) {
    begin[String(sequenceNumber)] = Int(Date().timeIntervalSince1970 * 1000)//AppDelegate.swift:185
    print("Send: \(Common.startCount)")
}

It works perfectly in my simulator and iPhone, but after made it available on AppStore, I received about 20 crash logs with some error like that:

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000000e7ffdefe
Triggered by Thread:  1
...
Thread 1 name:
Thread 1 Crashed:
0   ME                              0x0011e5cc specialized AppDelegate.simplePing(SimplePing, didSendPacket : Data, sequenceNumber : UInt16) -> () + 652 (AppDelegate.swift:185)
1   ME                              0x00116990 @objc AppDelegate.simplePing(SimplePing, didSendPacket : Data, sequenceNumber : UInt16) -> () + 68
2   ME                              0x00116818 @objc AppDelegate.simplePing(SimplePing, didSendPacket : Data, sequenceNumber : UInt16) -> () + 40
3   ME                              0x000f3348 -[SimplePing sendPingWithData:] + 640 (SimplePing.m:297)
...

I can't reproduce that crash, so I have to analysis that line of the code:

begin[String(sequenceNumber)]

begin initialized with begin = [String: Int](), so its type is [String : Int], and sequenceNumber's type is UInt16. So I think begin[String(sequenceNumber)] doesn't have any potential bug.

Int(Date().timeIntervalSince1970 * 1000)

And Int(Date().timeIntervalSince1970 * 1000) is just something like Int(aDouble * 1000), it seems correct in any situation.

So I get really confused with that crash log, could anyone please give me some hints?

Sayakiss
  • 6,878
  • 8
  • 61
  • 107

1 Answers1

3

From the docs for Int:

On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

A signed 32-bit integer has a maximum value of 2,147,483,647.

At the moment, Int(Date().timeIntervalSince1970 * 1000) returns a value of 1,495,855,170,970.

That is significantly larger than what will fit in a 32-bit integer.

The crash is being caused by the overflow you are attempting when casting the Double to an Int when run on a 32-bit iOS device.

I would suggest an explicit use of Int64 instead of Int:

begin[String(sequenceNumber)] = Int64(Date().timeIntervalSince1970 * 1000)
rmaddy
  • 314,917
  • 42
  • 532
  • 579