当malloc分配内存时它除了分配我们指定SIZE的内存块,还会分配额外的内存来存储我们的内存块信息,用于维护该内存块。因此,malloc(0)返回一个合法的指针并指向存储内存块信息的额外内存,我们当然可以在该内存上进行读写操作,但是这样做了会破坏该内存块的维护信息,因此当我们调用free(ptr)时就会出现错误。
#include<stdio.h>
#include<malloc.h>
struct student
{
char *name;//是指针 ,要给它分配内存的
float score;
}stu,p_stu;
void main()
{
char *p=NULL;
printf("pointer sizeof is %d\n",sizeof(p));///4
stu.name=(char *)malloc(20*sizeof(char)); //我原来 是 stu.name=(char *)malloc(1*sizeof(20));sizeof 是求字节数
printf("%d",sizeof(20));// is 4
strcpy(stu.name,"li ming");
stu.score=90;
printf("name is %s,score is %f\n",stu.name,stu.score);
free(stu.name);
stu.name=NULL;
p = malloc(0*sizeof(char));
if(NULL == p)
printf("got a NULL pointer\n");
else
printf("got a Valid pointer\n");
free(p);//给NULL 指针多次free 不会出错
free(p);
free(p);
/free(p);
}
好的程序:
#include<malloc.h>
struct student
{
char *name;
float score;
}*p_stu;
void main()
{
void *p=NULL;
printf("pointer sizeof is %d\n",sizeof(p));
p_stu=(char *)malloc(sizeof(struct student));
if(NULL==p_stu)
return ;
p_stu->name=(char *)malloc(20*sizeof(char));//同时也要给指针name分配内存,不然出错
if(NULL==p_stu->name)
return ;
strcpy(p_stu->name,"Li ming");
p_stu->score=90;
printf("name is %s,score is %f\n",p_stu->name,p_stu->score);
free(p_stu->name);
p_stu->name=NULL;
free(p_stu);
p_stu=NULL;
}
#include<stdio.h>
#include<malloc.h>
#include<string.h>
struct student
{
char name[20];
float score;
};
void main()
{
struct student *stu;
stu=(struct student *)malloc(sizeof(struct student));
strcpy(stu->name,"li ming");
stu->score=90;
printf("name is %s,score is %f\n",stu->name,stu->score);
free(stu);//此处出错
stu=NULL;
}