ARC&安培;的malloc:EXEC_BAD_ACCESS [英] ARC & Malloc: EXEC_BAD_ACCESS

查看:192
本文介绍了ARC&安培;的malloc:EXEC_BAD_ACCESS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经工作了一段时间一个项目现在,我决定将跳转到ARC。
我碰到一些code这是每一次轰炸了,我想知道这是为什么。我设法简化下来到这个片段:

I have been working on a project for some time now, and I decided to make the jump to 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;
}

我不太清楚这里发生了什么,厌倦了这种在4个不同的项目,他们都失败。是不是有什么毛病我的malloc 打电话?有时它返回null,其他时候它返回我无法访问的指针。

I'm not quite sure what is happening here, tired this in 4 different projects, and they all fail. Is there something wrong with my malloc call? Sometimes it returns null, and other times it returns a pointer that I can't access.

推荐答案

崩溃是因为你铸造malloc分配的内存对象的C数组。你试图给一个插槽的那一刻,ARC将释放previous价值,这将是垃圾内存。尝试使用释放calloc()而不是的malloc()来得到清零的内存,它应该工作。

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.

请注意,你的的realloc()通话也不会零填补所分配的新内存,所以如果你需要在 realloc()的则可能需要使用临时无效* 指针,你再手动分配给你的对象阵列之前填零为。

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.

这篇关于ARC&安培;的malloc:EXEC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆