c malloc freee

Posted on 2011-05-16 13:42 xsong 阅读(160) 评论(0)  编辑  收藏 所属分类: c
#include <stdio.h>
#include 
<stdlib.h>
#include
<string.h>

typedef 
struct{
    
int number;
    
char *msg;
} unit_t;

int main(void) {
    
// 使用 malloc 分配内存, 使用free释放内存,并设置为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访问内存
    free(p->msg);
    free(p);
    
//如果 free(p)  两次, 则会引发系统错误,
    p=NULL;

    
if(p==NULL){
        printf(
"p point is empty");
        exit(
-1);
    }

    
return EXIT_SUCCESS;
}

只有注册用户登录后才能发表评论。


网站导航: