3、懸掛指針
一個指針不為空,但是指向一個無效的地址或耒知對象的地址,則這樣的指針稱為懸掛指針。
dp@dp:~/memorytest % cat 2.c
#include#include //code:[email protected] //author:myhaspl //date:2014-01-10 typedef struct listnode mynode; struct listnode{ mynode *next; int number; int age; }; mynode *addnode(mynode *prevnd,int number,int age){ mynode *ndtemp=(mynode*)malloc(sizeof(mynode)); prevnd->next=ndtemp; ndtemp->number=number; ndtemp->age=age; ndtemp->next=NULL; return ndtemp; } mynode *initlist(){ mynode *temp=(mynode*)malloc(sizeof(mynode)); temp->number=0; temp->age=0; temp->next=NULL; return temp; } int main(){ mynode *mylist=initlist(); mynode *mytempnd=mylist; int i=0; for(i=0;i<10;i++){ mytempnd=addnode(mytempnd,i,20+i); } //下面是正常的鏈表操作 //先輸出鏈表元素 for (mytempnd=mylist->next;mytempnd!=NULL;mytempnd=mytempnd->next){ printf("id:%d,age:%d\n",mytempnd->number,mytempnd->age); } //然後刪除鏈表中的所有元素 mynode* oldtmpnd; for (mytempnd=mylist->next;mytempnd!=NULL;){ printf("delete id:%d\n",mytempnd->number); oldtmpnd=mytempnd; mytempnd=mytempnd->next; free(oldtmpnd); } free(mylist); //下面是形成內存洩露第二種情況-懸掛指針的演示 //生成並輸出鏈表,這個與前面相同 mylist=initlist(); mytempnd=mylist; i=0; for(i=0;i<10;i++){ mytempnd=addnode(mytempnd,i,20+i); } for (mytempnd=mylist->next;mytempnd!=NULL;mytempnd=mytempnd->next){ printf("id:%d,age:%d\n",mytempnd->number,mytempnd->age); } //我們故意刪除鏈表後面的4個節點,但是讓第6個元素的next指向的地址無效, //仍指向已經刪除的第7個節點,導致懸掛指針 printf ("-------------------------\n"); int j=0; for (mytempnd=mylist->next;mytempnd!=NULL;){ oldtmpnd=mytempnd; mytempnd=mytempnd->next; if (++j>6){ printf("delete id:%d\n",oldtmpnd->number); free(oldtmpnd); } } return 0; }
執行程序
dp@dp:~/memorytest % gcc 2.c -o mytest
dp@dp:~/memorytest % ./mytest
id:0,age:20
id:1,age:21
id:2,age:22
id:3,age:23
id:4,age:24
id:5,age:25
id:6,age:26
id:7,age:27
id:8,age:28
id:9,age:29
delete id:0
delete id:1
delete id:2
delete id:3
delete id:4
delete id:5
delete id:6
delete id:7
delete id:8
delete id:9
id:0,age:20
id:1,age:21
id:2,age:22
id:3,age:23
id:4,age:24
id:5,age:25
id:6,age:26
id:7,age:27
id:8,age:28
id:9,age:29
-------------------------
delete id:6
delete id:7
delete id:8
delete id:9
但是注意free函數表示釋放,這個釋放指的是把這段內存標記成可用狀態,或者說,沒有人在用這段內存了,也就是意味著如果這段內存如果沒有被操作系統重新使用,裡面的數據還存在,如果被操作系統分配給其它程序或本程序的其它內存塊申請之用,則數據會被清空。