#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct{
int number;
char *msg;
} unit_t;
int main(void) {
// 使用 malloc 分配內(nèi)存, 使用free釋放內(nèi)存,并設置為NULL 杜絕野指針
unit_t *p=malloc(sizeof(unit_t));
p->number=10;
p->msg=malloc(10);
strcpy(p->msg,"hello");
printf("number is %i \n",p->number);
printf("msg is %s \n",p->msg);
//如果先free(p),p成了野指針,就不能再通過p->msg訪問內(nèi)存
free(p->msg);
free(p);
//如果 free(p) 兩次, 則會引發(fā)系統(tǒng)錯誤,
p=NULL;
if(p==NULL){
printf("p point is empty");
exit(-1);
}
return EXIT_SUCCESS;
}
#include <stdlib.h>
#include<string.h>
typedef struct{
int number;
char *msg;
} unit_t;
int main(void) {
// 使用 malloc 分配內(nèi)存, 使用free釋放內(nèi)存,并設置為NULL 杜絕野指針
unit_t *p=malloc(sizeof(unit_t));
p->number=10;
p->msg=malloc(10);
strcpy(p->msg,"hello");
printf("number is %i \n",p->number);
printf("msg is %s \n",p->msg);
//如果先free(p),p成了野指針,就不能再通過p->msg訪問內(nèi)存
free(p->msg);
free(p);
//如果 free(p) 兩次, 則會引發(fā)系統(tǒng)錯誤,
p=NULL;
if(p==NULL){
printf("p point is empty");
exit(-1);
}
return EXIT_SUCCESS;
}
posted @ 2011-05-16 13:42 xsong 閱讀(173) | 評論 (0) | 編輯 收藏