malloc 定义为: void *malloc(unsigned int)
C使用void 服务于两个目的:
(1) 在函数定义中作为一种类型时,void 表示函数没有返回值。
(2) 用作指针定义时,void 定义一个通用指针(可以指向任何数据类型)。
函数malloc只有一个自变量:分配的字节数。如果malloc用光了内存,将返回一个空指针(可指向任意数据类型)。下面的一段代码为自定义数据结构person申请内存。
struct
person
...
{
char name[30];
char addr[30];
int age;
float height;
}
struct person * ptr = malloc( sizeof ( struct person));
if ( ptr == NULL ) ... {
fprintf( stderr, " Out of memory! ");
exit(8);
}
char name[30];
char addr[30];
int age;
float height;
}
struct person * ptr = malloc( sizeof ( struct person));
if ( ptr == NULL ) ... {
fprintf( stderr, " Out of memory! ");
exit(8);
}
malloc 函数为变量分配存储空间,然后返回指针,它用于在一个称为堆栈(heap)的内存空间里创建新实体。堆栈的大小虽然很大,但毕竟有限。malloc 用完内存后将返回NULL 指针。好的程序方法应告诉你检查每个malloc 调用的返回值(如上面代码中的if 语句部分),以确保真的得到了内存。
free 函数
在处理结束之后,使用free 函数释放内存。下面的一段代码用malloc 得到内存并释放它:
const
int
DATA_SIZE
=
(
16
*
1024
);
/*
apply for 16KB
*/
void copy( )
{
char * data_buffer;
data_buffer = malloc(DATA_SIZE);
/*
* Use the data buffer to copy a file.
*/
free(data_buffer);
data_buffer = NULL:
}
void copy( )
{
char * data_buffer;
data_buffer = malloc(DATA_SIZE);
/*
* Use the data buffer to copy a file.
*/
free(data_buffer);
data_buffer = NULL:
}
使用free的一般形式是:
free (pointer);
pointer = NULL;
注意:不一定非要把指针设为NULL,但设为NULL可以阻止使用释放后的内存。调用free后使用指针,将有可能发生一个类似于数组下标超界的错误,因为你使用的是属于别的程序的内存空间,这可能会得到意想不到的结果,甚至使程序崩溃。