What is causing this EXC_BAD_ACCESS error?

I get a EXC_BAD_ACCESS error in this code at the end where the constant “line” is declared. At the line that says “let line: CTLine = CTLineCreateWithAttributedString(attrString)”. The exact error says “Thread 2: EXC_BAD_ACCESS (code=1, address=0x7e8))”.

Can I get some help identifying the problem?

And how do I debug this?

I set the debug settings to use zombies but I get no zombie messages either in Xcode or in the Zombies Instrument.

import UIKit
import MapKit
import CoreText

class LabelOverlayRenderer: MKOverlayRenderer {

    override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
        let string: CFString
        let font: CTFont
        let nsString = NSString(string: "Hello" as CFString)
        string = nsString as CFString
        font = CTFontCreateUIFontForLanguage(.label, 17, "US" as CFString)!
        var keys: [CFString] = [kCTFontAttributeName]
        var values: [CFTypeRef] = [font]
        var mutablePointerKeys: UnsafeMutablePointer<UnsafeRawPointer?>!
        var rawPointerKeys: UnsafeRawPointer?
        rawPointerKeys = UnsafeRawPointer?(&keys)
        mutablePointerKeys = UnsafeMutablePointer<UnsafeRawPointer?>!(&rawPointerKeys)
        var mutablePointerValues: UnsafeMutablePointer<UnsafeRawPointer?>!
        var rawPointerValues: UnsafeRawPointer?
        rawPointerValues = UnsafeRawPointer?(&values)
        mutablePointerValues = UnsafeMutablePointer<UnsafeRawPointer?>!(&rawPointerValues)
        var cfTypeDictionaryKeyCallBacks = CFDictionaryKeyCallBacks()
        var cfTypeDictionaryValueCallBacks = CFDictionaryValueCallBacks()
        let attributes: CFDictionary = CFDictionaryCreate(kCFAllocatorDefault, mutablePointerKeys, mutablePointerValues, MemoryLayout.size(ofValue: keys)/MemoryLayout.size(ofValue: keys[0]), &cfTypeDictionaryKeyCallBacks, &cfTypeDictionaryValueCallBacks)
        let attrString: CFAttributedString = CFAttributedStringCreate(kCFAllocatorDefault, string, attributes)
        let line: CTLine = CTLineCreateWithAttributedString(attrString) // Error occurs here saying "Thread 2: EXC_BAD_ACCESS (code=1, address=0x7e8)"
        context.textPosition = CGPoint(x: 10, y: 10)
        CTLineDraw(line, context)

@brower. Thanks very much for your question!

Given what you’re saying, I would check to see if the property, “attrString” is valid when creating the “line” constant. What I would also do is put some breakpoints higher up, slowly step through your function, and see what values your properties have prior to the error occurring.

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.