简体   繁体   English

ARC&Malloc:EXEC_BAD_ACCESS

[英]ARC & Malloc: EXEC_BAD_ACCESS

I have been working on a project for some time now, and I decided to make the jump to ARC. 我一直在做一个项目已经有一段时间了,我决定跳到ARC。 I came across some code that was bombing out every time, and I would like to know why. 我偶然发现了一些轰炸的代码,我想知道为什么。 I have managed to simplify it down to this snippet: 我已设法将其简化为此代码段:

typedef __strong id MYID;

int main(int argc, char *argv[])
{ 
    MYID *arr = (MYID *) malloc(sizeof(MYID) * 4);

    arr[0] = @"A";     // always get an EXEC_BAD ACCESS HERE
    arr[1] = @"Test";
    arr[2] = @"Array";
    arr[3] = @"For";

    // uh oh, we need more memory
    MYID *tmpArray = (MYID *) realloc(arr, sizeof(MYID) * 8);
    assert(tmpArray != NULL);

    arr = tmpArray;

    arr[4] = @"StackOverflow";  // in my actual project, the EXEC_BAD_ACCESS occurs here
    arr[5] = @"Is";
    arr[6] = @"This";
    arr[7] = @"Working?";

    for (int i = 0; i < 8; i++) {
        NSLog(@"%@", arr[i]);
    }

    return 0;
}

I'm not quite sure what is happening here, tired this in 4 different projects, and they all fail. 我不太确定这里发生了什么,在4个不同的项目中厌倦了这些,而且都失败了。 Is there something wrong with my malloc call? 我的malloc电话有问题吗? Sometimes it returns null, and other times it returns a pointer that I can't access. 有时它返回null,有时它返回一个我无法访问的指针。

The crash is because you're casting malloc'd memory to a C array of objects. 崩溃是因为您将malloc内存转换为C对象数组。 The moment you try to assign to one of the slots, ARC will release the previous value, which will be garbage memory. 当您尝试分配给其中一个插槽时,ARC将释放先前的值,这将是垃圾内存。 Try using calloc() instead of malloc() to get zeroed memory and it should work. 尝试使用calloc()而不是malloc()来获取归零内存,它应该工作。

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. 请注意,你的realloc()调用也不会零填充已分配的任何新内存,因此如果你需要realloc()那么你可能想要使用一个临时的void*指针,然后在分配给你之前手动归零。对象数组。

The malloc function does not zero the memory it allocates. malloc函数不会将其分配的内存归零。 The memory can contain random garbage. 内存可以包含随机垃圾。

From the Clang Automatic Reference Counting guide, section 4.2: Clang自动参考计数指南,第4.2节:

For __strong objects, the new pointee is first retained; 对于__strong对象,首先保留新的指针对象; 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. 所以这里可能发生的是malloc返回包含随机非零值的内存。 ARC tries to use that random value as a pointer to an object and release it, but it's not a valid object pointer. ARC尝试使用该随机值作为指向对象的指针并释放它,但它不是有效的对象指针。 Crash. 崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM