背景:我不了解C ++,我了解C。
Problem: In a file called lruTable.hh
, I have defined
struct lnode {
struct lnode *next;
struct lnode *prev;
};
struct Table {
struct lnode *list;
int size;
};
class lruTable {
private:
struct Table *table;
public:
lruTable();
};
I want the class constructor lruTable()
to initialize the private variable table
such that table->list
is the head of a doubly linked list, and should be initialized to point to itself in both directions. In a file called lruTable.cc
, I have the constructor as
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;
}
I have verified that lnconst()
initializes list heads like I want it to. In fact, running the GDB, at line A, the Table t
is exactly as I want it to be with t->list->next == t->list
and t->list->prev == t->list
. However, once TableAlloc()
returns in the constructor, something goes wrong and what I have instead is that table->list->next == table->list
(desired) and table->list->prev == table
(incorrect). I have verified this by printing addresses in GDB.
下一行未分配正确的内存量。
您需要使用
关于您的代码的几点。
In C++, you don't need to use
struct Table
andstruct lnode
after they have been declared. You can simply useTable
andlnode
.Don't use
malloc
/free
. Usenew
anddelete
.Your malloc in
lnconst
is not for enough memory:malloc(sizeof(struct lnode *));
will provide size for a pointer, not for a fullstruct lnode
.With that, the memory where you store
prev
is not yours, and it will change whenever it likes (depending on compiler's / OS' memory layout).Obviously, you need to use
malloc(sizeof(struct lnode));
.