objective-cxcode

what's the difference between code=1 and code=2 in EXC_BAD_ACCESS?


I am receiving code=1 or code=2 for EXC_BAD_ACCESS error. I am wondering what's the difference between code=1 and code=2?


Solution

  • Code = 1 is KERN_INVALID_ADDRESS and code = 2 is KERN_PROTECTION_FAILURE. Both are explained in the "Technical Note TN2123 CrashReporter":

    The most common forms of exception are:

    • EXC_BAD_ACCESS/KERN_INVALID_ADDRESS — This is caused by the thread accessing unmapped memory. It may be triggered by either a data access or an instruction fetch; the Thread State section describes how to tell the difference.
    • EXC_BAD_ACCESS/KERN_PROTECTION_FAILURE — This is caused by the thread trying to write to read-only memory. This is always caused by a data access.

    The codes are defined in <mach/kern_return.h>:

    #define KERN_INVALID_ADDRESS            1
                    /* Specified address is not currently valid.
                     */
    
    #define KERN_PROTECTION_FAILURE         2
                    /* Specified memory is valid, but does not permit the
                     * required forms of access.
                     */
    

    and in <mach/exception_types.h> it is documented that the code for a EXC_BAD_ACCESS is a kern_return_t:

    #define EXC_BAD_ACCESS          1       /* Could not access memory */
                    /* Code contains kern_return_t describing error. */
                    /* Subcode contains bad memory address. */