首页 > 解决方案 > 正确分配私有变量

问题描述

背景:我不懂C++,我懂C。

问题:在一个名为的文件lruTable.hh中,我定义了

struct lnode {
    struct lnode *next;
    struct lnode *prev;
};

struct Table {
    struct lnode *list;
    int size;
};

class lruTable {

private:
    struct Table *table;
public:
    lruTable();

};

我希望类构造函数lruTable()初始化私有变量table,使其table->list成为双向链表的头部,并且应该初始化为在两个方向上指向自身。在一个名为 的文件lruTable.cc中,我的构造函数为

lruTable::lruTable() {
    table = TableAlloc();
}

和表分配器为

struct Table *TableAlloc(void) {
    struct Table *t = (struct Table *) malloc(sizeof(struct Table));
    if (t == NULL) {
        fprintf(stderr, "[ERROR] %s:%d: malloc failed\n", __FILE__, __LINE__);
        exit(EXIT_FAILURE);
    }

    t->size = 0;
    t->list = lnconst(); // A
    return t;
}

最后,lnode 分配器为

struct lnode *lnconst(void) {

        struct lnode *ln = (struct lnode *) malloc(sizeof(struct lnode *));
        if (ln == NULL) {
            fprintf(stderr, "[ERROR] %s:%d: malloc failed\n", __FILE__, __LINE__);
            exit(EXIT_FAILURE);
        }

        ln->next = ln;
        ln->prev = ln;
        return ln;
}

我已经验证了lnconst()它可以像我想要的那样初始化列表头。事实上,在运行 GDB 时,在 A 行,表格t正是我想要的,它带有t->list->next == t->listand t->list->prev == t->list。但是,一旦TableAlloc()在构造函数中返回,就会出现问题,而我所拥有的是table->list->next == table->list(期望的)和table->list->prev == table(不正确的)。我已经通过在 GDB 中打印地址来验证这一点。

标签: c++

解决方案


您的 malloc inlnconst内存不足:
malloc(sizeof(struct lnode *));将为指针提供大小,而不是为完整的struct lnode.

这样,您存储的内存prev就不是您的了,它会随时更改(取决于编译器/操作系统的内存布局)。

显然,您需要使用malloc(sizeof(struct lnode));.


推荐阅读