typedef struct DNode{
int data;
struct DNode *lLink,*rLink;
} DblNode;
typedef DblNode * DblList;
void DestroyDblList(DblList L){
DblList head=L;
DblList p=head->rLink;
if(head->data){ //p->data is wrong?
while(p->data){
free(head);
head=p;
p=head->rLink;
}
free(head);
}
}
At the line with comments, when I use if(p->data){
my computer tells me
Segmentation fault (core dumped)
but when I use if(head->data){
it is OK.
How did it happen,what is the cause of it?
In your code p->data
is same as head->rLink->data
, where head->rLink
is not allocated memory. So, segmentation fault [as a side effect of undefined behavior .].
On other hand, head->data
is a perfect access.
BTW, you understand that p->data
and head->data
are not same [at line 56
], right?
p->data
and head->data
would be the same if p
and head
would be the same. In line 56 this can only be true if head
is the same as head->rLink
by line 55, ie head
points to itself which contradicts the understanding of a double linked list.
So p->data
and head->data
must be different.
您应该测试p
的无效性,而不是p->data
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.