How to debug EXC_BAD_ACCESS bug

半世苍凉 提交于 2019-11-28 20:22:27

To debug an EXC_BAD_ACCESS, you can generally find out the where the dangling pointer is by enabling zombie objects.

Xcode

Choose edit scheme, then Diagnostics tab in the Run section, then click the 'Zombie Objects' option.

AppCode

Choose edit target, and add the following environment variable:

NSZombieEnabled=YES

Another cause for EXC_BAD_ACCESS can be infinite recursion, which can be found by adding some logging.

Update for C++:

To debug dangling pointers in C++ with the Clang compiler try using Address Sanitizer (ASAN) from Google.

It looks like maybe you are trying to write onto a code page or something? EXC_BAD_ACCESS is described in /usr/include/mach/exception_types.h:

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

And from kern_return.h:

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

You can see WHERE that address is in your binary by doing:

(lldb) image lookup -va 0xb0987654

But what you really need to figure out is who is trying to write there. If the problem is simple this might tell you what's wrong, but as Jasper suggests, this is probably some use-after-free or other such problem, and the bad actor is long gone by the time you crash. guardmalloc can also sometimes catch this sort of error (you can enable this in Xcode in the Run scheme.)

Identify what you did that caused the crash. Did it crash while view of a particular view controller didLoad or in a delegate method or on a particular action. That will often help to find the object that is casuing the error.

  • Most of the time “NSZombies” can help to identify the dead object. You can enable NSZombies by editing your scheme Product -> Edit Scheme -> Diagnostics.
  • If you still don’t find the root cause then always go backwards from child view controller to parent view controller to see what object needs to be retained or what message needs to be passed properly.
  • Look into Static Analyzer and Instruments for advanced debugging.

I hope this will help you.

Regards, Gison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!