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;
char *data;
int number;
int age;
};
mynode *addnode(mynode *prevnd,int number,int age,char *data){
mynode *ndtemp=(mynode*)malloc(sizeof(mynode));
prevnd->next=ndtemp;
ndtemp->number=number;
ndtemp->age=age;
ndtemp->data=data;
ndtemp->next=NULL;
return ndtemp;
}
mynode *initlist(){
mynode *temp=(mynode*)malloc(sizeof(mynode));
temp->number=0;
temp->age=0;
temp->data=NULL;
temp->next=NULL;
return temp;
}
int main(){
//下面是形成內存洩露第三種情況-共享的演示,多個指針指向同一個內存,這個內存因為某個指針不再使用的原因刪除,
//生成並輸出鏈表,生成1個鏈表(共3個元素),元素的data都指向同一個內存塊
mynode *mylist=initlist();
mynode *mytempnd=mylist;
char *mydata=(char *)malloc(100);
const char *strsrc="helloworld";
strcpy(mydata,strsrc);
int i=0;
for(i=0;i<3;i++){
mytempnd=addnode(mytempnd,i,20+i,mydata);
}
for (mytempnd=mylist->next;mytempnd!=NULL;mytempnd=mytempnd->next){
printf("id:%d,age:%d,data:%s\n",mytempnd->number,mytempnd->age,mytempnd->data);
}
//下面將導致共享的內存釋放,但仍有2個結點指向這個內存,這將導致內存洩露
//我們故意刪除最後一個節點,並釋放最後一個結點的data指針指向的內存
printf ("-------------------------\n");
mynode *oldtmpnd;
for (mytempnd=mylist->next;mytempnd!=NULL;){
oldtmpnd=mytempnd;
mytempnd=mytempnd->next;
if (mytempnd==NULL){
printf("delete id:%d\n",oldtmpnd->number);
free(oldtmpnd->data);
free(oldtmpnd);
}
}
return 0;
}
執行程序:
dp@dp:~/memorytest % gcc 2.c -o mytest
2.c: In function 'main':
2.c:37: warning: incompatible implicit declaration of built-in function 'strcpy'
dp@dp:~/memorytest % ./mytest
id:0,age:20,data:helloworld
id:1,age:21,data:helloworld
id:2,age:22,data:helloworld
-------------------------
delete id:2
dp@dp:~/memorytest %