c++ - 正确分配私有变量
问题描述
背景:我不懂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->list
and t->list->prev == t->list
。但是,一旦TableAlloc()
在构造函数中返回,就会出现问题,而我所拥有的是table->list->next == table->list
(期望的)和table->list->prev == table
(不正确的)。我已经通过在 GDB 中打印地址来验证这一点。
解决方案
您的 malloc inlnconst
内存不足:
malloc(sizeof(struct lnode *));
将为指针提供大小,而不是为完整的struct lnode
.
这样,您存储的内存prev
就不是您的了,它会随时更改(取决于编译器/操作系统的内存布局)。
显然,您需要使用malloc(sizeof(struct lnode));
.
推荐阅读
- javascript - 使用循环更改背景颜色
- javascript - UnhandledPromiseRejectionWarning:MongoError:无法使用已结束的会话
- javascript - 如果条件为真或假,我们可以在组件内传递三元表达式并作为道具发送吗
- html - 无法部分返回从标题生成的图像 - Hugo
- html - 1 多个播放器的音量控制器?
- raspberry-pi - bluetoothctl 不显示蓝牙低功耗 (BLE) 设备
- bash - bash 导出未包含在 kubectl 命令中
- python - Flask Python 如何将输入从文本框传递到 POST 请求?
- r - 带有 facet_wrap 的 cowplot::plot_grid - y 轴标题与轴标签重叠
- python - 如何以这种方式平铺张量?(张量流)