c语言的malloc和free函数
STUDY OF COMPUTER APPLICATION IN EDUCATION 计计算机应用教学研究算机应用教学研究
C 语言的malloc 和free 函数
聂芬
(山西水利职业技术学院,运城044000)
摘 要: C 语言程序在运行期间的内存管理主要靠malloc 和free 函数实现,这部分内存由程序员使用malloc 申请分
配,用free 释放该内存。本文主要介绍malloc 和free 函数的使用。
关键词:C 语言;内存;函数
The Function Malloc and Free in C Language
NIE Fen
(Shanxi Water Technics Professional College, Yuncheng 044000)
Abstract :The C language program of memory management during the period of operation is depends on the function malloc
and free .The memory allocated by the programmer to use the function malloc,released to use the function free .The article
describes the function malloc and free to use.
Key words: C Language; Memory; Function
1 引言 int num;
在C 语言的开发学习中,经常要进行内存分配,动态内 char *name;
char sex;
存分配技术可以保证在程序运行过程中按照实际需要申请适
float score;
量的内存,使用结束后释放。C 语言跟内存申请相关的函数主
} *ps;
要有alloca、calloc、malloc、free 、realloc 、sbrk 等。在实际学 ps= (struct stu*) malloc (sizeof (struct stu)) ;
习中主要通过调用库函数malloc () 和free () 来进行内存的分 ps->num=102;
配和释放。 ps->name=”Zhang ping”;
ps->sex= ’M ’;
2 函数的基本用法
ps->score=62.5;
2.1 分配内存函数malloc printf (“Number=%d\nName=%s\n”,ps->num,ps->name) ;
调用形式: (类型说明符 *) malloc (size) ; printf (“Sex=%c\nScore=%f\n”,ps->sex,ps->score)