内存访问错误 - 异常 (C++)

Bad access of memory - exception (C++)

我在倒数第 3 行得到 EXC_BAD_ACCESS (code=1, address=0x0),其中我 return 一个 *Bitvector。正如您在 main 中看到的那样,我尝试将第 10 个索引翻转为 1。我高度怀疑我管理内存的方式是原因,但无法弄清楚在哪里以及如何。 (注意BinTree没有完成,我用的是mac,我用的是vs-code)

struct node {
    BitVector b;
    node* parent;
    node* right;
    node* left;
};

class BinTree {

    node* root;
    node* insert(node* t, int g) {
        if (t==NULL) {
            t->b.get_bitvector()->at(g) = 1; //Here I try to set the g'th index to be 1 in the bitvector.
        }
        return t;
}

public:
    BinTree() {
        root = NULL;
    }

    void insert(int g) {
        root = insert(root, g);
    }
};


class BitVector {
    vector<short>* bitvector; // construct a pointer
public:
    BitVector() {
        bitvector = new vector<short>(30); // point the pointer to a vector of size 30.
    }
    vector<short>* get_bitvector() {
        return bitvector; //Exception occurs here
    }
};



int main() {
    BinTree t;
    t.insert(10);
}

EXC_BAD_ACCESS 当您尝试访问应用程序未分配的内存时发生;应用程序没有访问权限。
我想错误是因为您没有向树中添加节点。你只是在打电话给他们。在这里:if (t==NULL)t->b.get_bitvector()->at(g) 仅在节点地址为 0x0 时才被调用,因此出现错误。

你应该做的是,如果以某种方式找不到节点,则添加一个逻辑并将 t==NULL 更改为 t!=NULL

注意:在使用指针时尝试使用 nullptr 并放弃 NULL

您的程序有两点失败。

首先,你必须检查 bintree->t 是否为 NOT null:

if (t != NULL) {
            t->b.get_bitvector()->at(g) = 1; 
}

其次,您必须使用位向量而不是 NULL 来初始化您的 bintree->t:

public:
    BinTree() {
        root = new BitVector();
    }