ARC & Malloc: EXEC_BAD_ACCESS

丶灬走出姿态 提交于 2019-12-05 08:48:27

The crash is because you're casting malloc'd memory to a C array of objects. The moment you try to assign to one of the slots, ARC will release the previous value, which will be garbage memory. Try using calloc() instead of malloc() to get zeroed memory and it should work.

Note that your realloc() call will also not zero-fill any new memory that's allocated, so if you need the realloc() then you may want to be using a temporary void* pointer that you then zero-fill manually before assigning to your object array.

The malloc function does not zero the memory it allocates. The memory can contain random garbage.

From the Clang Automatic Reference Counting guide, section 4.2:

For __strong objects, the new pointee is first retained; second, the lvalue is loaded with primitive semantics; third, the new pointee is stored into the lvalue with primitive semantics; and finally, the old pointee is released.

So what's probably happening here is malloc is returning memory that contains random non-zero values. ARC tries to use that random value as a pointer to an object and release it, but it's not a valid object pointer. Crash.

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