我在创建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()
在上面。
答案 0 :(得分:1)
这是我能想象的唯一理性方式(到目前为止)......
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);
}
}
答案 1 :(得分:0)
您在知道a
这里是
null
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
。
在知道b
是否null
之前,你也取消引用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 ....
}
至少做:
TFramedTransport