?malloc? ralloc realloc
free
原则:谁申请,谁释放(防止内存泄漏)free
malloc函数
函数原型
void *malloc(size_t size);
返回值:
成功:返回一个非空指针
失败:返回NULL
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int main()
{
int *p =NULL;
p = malloc(sizeof(int));
if(p == NULL)
{
printf("malloc() error!\n");
exit(1);
}
*p = 10;
printf("%d\n",*p);
free(p);
exit(1);
}
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int main()
{
int *p;
int num = 5;
p = malloc(sizeof(int) *num);
for(int i=0;i < num;i++)
{
scanf("%d",&p[i]);
}
for(int i=0;i<num;i++)
printf("%d",p[i]);
printf("\n");
free(p);
exit(0);
}
面试常问的内存泄漏
#include <stdio.h>
#include <stdlib.h>
#if 0
void func(int **p,int n)
{
*p = malloc(n);
if(p == NULL)
{
exit(1);
}
return ;
}
#else
void *func(int *p,int n)
{
p= malloc(n);
if(p == NULL)
exit(1);
return p;
}
#endif
int main()
{
int num = 100;
int *p = NULL;
p = func(p,num);
free(p);
exit(0);
}
free的使用及微型学生管理系统的代码重构
动态内存管理
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMEMAX 1024
struct student_st{
int id;
char *name;
int math;
int chinese;
};
void stu_set(struct student_st *p,struct student_st *q)
{
p->id = q->id;
p->name = malloc(strlen(q->name)+1);
if(p->name == NULL)
exit(1);
strcpy(p->name,p->name);
p->math = q->math;
p ->chinese = q->chinese;
}
void stu_show(struct student_st *p)
{
printf("%d %s %d %d\n",p->id,p->name,p->math,p->chinese);
}
void stu_changename(struct student_st *p,const char *newname)
{
free(p->name);
p->name = malloc(strlen(newname)+1);
strcpy(p->name,newname);
}
void menu(void)
{
printf("\n1 set\n2 change name\n3 show\n");
printf("Please enter the num:");
}
int main()
{
struct student_st stu,tmp;
char newname[NAMEMAX];
int choice;
int ret;
do{
menu();
ret = scanf("%d",&choice);
if(ret != 1)
break;
switch(choice)
{
case 1:
tmp.name = malloc(NAMEMAX);
printf("please enter for the stu[id name math chinese]:");
scanf("%d%s%d%d",&tmp.id,tmp.name,&tmp.math,&tmp.chinese);
stu_set(&stu,&tmp);
break;
case 2:
printf("please enter the newname:");
scanf("%s",newname);
stu_changename(&stu,newname);
break;
case 3:
stu_show(&stu);
break;
default:
exit(1);
}
sleep(1);
}while(1);
exit(0);
}
|