栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

19.C语言 动态内存分配---malloc和realloc的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

19.C语言 动态内存分配---malloc和realloc的使用

 malloc  ralloc realloc

free

原则:谁申请,谁释放(防止内存泄漏)free

malloc函数

函数原型

void *malloc(size_t size);

返回值:

成功:返回一个非空指针

失败:返回NULL

#include 
#include 
#include 
int main()
{
        int *p =NULL;

        p = malloc(sizeof(int));
        if(p == NULL)
        {
                printf("malloc() error!n");
                exit(1);
        }

        *p = 10;

        printf("%dn",*p);

        free(p);
        exit(1);
}

#include 
#include 
#include 
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 

面试常问的内存泄漏

#include 
#include 
#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 
#include 
#include 

#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 %dn",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 setn2 change namen3 shown");
	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);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号