我一直在创建concat();
函数时遇到问题,它可以工作,但是当我继续释放列表时,我收到malloc
错误...我肯定我正在正确释放我的列表,当我不运行我的concat();
函数时,列表会正确释放。这就是我有理由相信我在这个函数中做错了什么......
typedef struct node {
ElemType val;
struct node *next;
} NODE;
struct list_struct {
NODE *front;
NODE *back;
};
void lst_concat(LIST *a, LIST *b) {
if( !( a->front && b->front)) return ;
if (a->front == NULL && b->back == NULL) {
return;
}
if (a->front == NULL && b->front != NULL) {
a->front = b->front;
return;
}
else{
NODE *tmp = a->front;
if( a->back == NULL )return;
if( a->front == NULL )return;
if( b->back == NULL )return;
if( b->front == NULL )return;
else{
NODE *tempPtr = a->back;
tempPtr->next=b->front;
tempPtr = b->front;
a->back = b->back;
}
}}
void lst_free(LIST *l) {
NODE *p = l->front;
NODE *pnext;
while(p!= NULL) {
pnext = p->next; // keeps us from de-referencing a freed ptr
free(p);
p = pnext;
}
// now free the LIST
free(l);
}
**更新,此更新列表正确,但是,我仍然可以释放两个列表,还是在它们加入后只能释放一个列表? 我的lst_free()
在上面。
这是我
能想象到的唯一合理的方式(到目前为止)......
typedef struct NODE NODE;
typedef struct list_struct LIST;
typedef struct node {
ElemType val;
NODE *next;
} NODE;
struct list_struct {
NODE *front;
NODE *back;
};
// get the ending node
NODE *LastNode(NODE *root){
NODE *tmp = NULL;
while(root){
tmp = root;
root = root->next;
}
return tmp;
}
// this will move node from pnode
// and put it at the end of proot nodes
void move_node(NODE **proot,NODE **pnode){
if(! (pnode && proot) )
return; // no comments
if(pnode == proot)
return; // no comments
NODE *node = *pnode;
NODE *root = *proot;
NODE *tmp;
if(!node) return;
if(!root){
// this node becomes the first one
*proot = node;
}else{
// this node becomes the last node
LastNode(root)->next = node;
}
// now nodes blongs to other node
// set this to NULL
*pnode = NULL;
}
// this will move a nodes to b;
//
void lst_concat(LIST *a, LIST *b) {
move_node(&a->front, &b->front);
move_node(&a->back, &b->back);
// at this point b has no front, and no back
// all has been moved to a
}
void free_nodes(NODE **proot){
if ( !(proot && *proot) )
return;
NODE *root = *proot;
if( root->next)
free_nodes(&root->next);
free(root);
*proot=NULL;
}
void lst_free(LIST *l) {
if( l ) {
free_nodes( &l->front);
free_nodes( &l->back);
free(l);
}
}
在知道它是否null
之前,您正在取消引用a
:
void concat(LIST *a, LIST *b)
{
if (a->front == NULL) { // !!!! what if a is NULL? Crash...
a->front = b->front;
a->back = b->back;
return;
}
首先检查a
是否NULL
。
在知道它是否null
之前,您也在取消引用b
:
void concat(LIST *a, LIST *b)
{
if (a->front == NULL) {
a->front = b->front; // !!!! what if b is NULL? Crash...
a->back = b->back;
return;
}
至少做到:
void concat(LIST *a, LIST *b)
{
if (a == NULL) // This needs to go first, i.e. before dereferencing a
{
// some code
}
// other code ....
}