首页 > 解决方案 > C 指针错误,得到 exc_bad_access 代码=2,地址 0x100000000

问题描述

我对这个错误感到很困惑。我写了一个代码来分隔一组。当我运行它时,有时它可以工作,有时会出现 exc_bad_access code=2 错误。这是代码:

typedef struct vertexSet {
    int numVertexSet;
    int* set1;
    int* set2;
} set;

set* bipatitionSet(int Vertex) {

    if (Vertex%2){
        Vertex +=1;
    }

    set* set;
    set = malloc(sizeof(set));
    set->numVertexSet = Vertex/2;
    set->set1 = calloc(set->numVertexSet,sizeof(int));
    set->set2 = calloc(set->numVertexSet,sizeof(int));

    if (set == NULL) {
        printf("Set memory allocated error!");
        exit(1);
    }

    if (set->set1 ==NULL||set->set2==NULL) {
        free(set);
        printf("Set memory allocated error!");
        exit(1);
    }

    for (int i=0; i< set->numVertexSet; i++) {
        set->set1[i] = i;
        set->set2[i] = i + set->numVertexSet;// got error here
    }

    return set;
}

运行时发现在for循环中set2地址发生了变化,set2[0]的值变成了-17958193。此错误有时会出现,但并非总是出现。有人可以解释为什么以及如何解决该错误吗?我检查了没有地址冲突。

标签: cxcodepointersexc-bad-access

解决方案


您不应该将变量命名为与类型相同的名称,因为变量会影响类型(您如何理解自己的代码,并区分类型和变量?)。在这种情况下,“阴影”与“覆盖”的含义相似。

作为一个例子,你malloc是不正确的,因为sizeof(set)将是变量的大小set,一个简单的 4 或 8 字节指针,而不是 12-20 字节的大小struct vertexSet


推荐阅读