free ()- 释放存储块
格式
#include <stdlib.h>
void free(void *ptr);语言级别
ANSI
线程安全
是
描述
free() 函数释放存储器块。 ptr 自变量指向先前通过调用 calloc(), malloc(), realloc(), _C_TS_calloc(), _C_TS_malloc(), _C_TS_realloc()或 _C_TS_malloc64() 函数保留的块。 释放的字节数是在保留 (或重新分配 (对于 realloc() 函数) 存储器块时) 指定的字节数。 如果 ptr 为 NULL,那么 free() 仅返回。注:
- 所有堆存储器都与调用函数的激活组相关联。 因此,应该在同一激活组中分配,取消分配和重新分配存储器。 在一个激活组中分配堆存储器并从另一个激活组中取消分配或重新分配该存储器是无效的。 有关激活组的更多信息,请参阅 ILE 概念 手册。
- 尝试释放未与
calloc(),malloc()或realloc()(或先前释放的存储器) 一起分配的存储器块可能会影响存储器的后续保留,并导致未定义的结果。 可以使用free()来释放使用 ILE 可绑定 API CEEGTST 分配的存储器。
要在不更改 C 源代码的情况下使用 太字节空间 存储器而不是单层存储器,请在编译器命令上指定 TERASPACE (*YES *TSIFC) 参数。 这会将 free() 库函数映射到 _C_TS_free()(其太字节空间存储器对等项)。
返回值
没有返回值。
示例
此示例使用
calloc() 函数为 x 数组元素分配存储器,然后调用 free() 函数以释放这些元素。#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long * array; /* start of the array */
long * index; /* index variable */
int i; /* index variable */
int num; /* number of entries of the array */
printf( "Enter the size of the array\n" );
scanf( "%i", &num );
/* allocate num entries */
if ( (index = array = calloc( num, sizeof( long ))) != NULL )
{
for ( i = 0; i < num; ++i ) /* put values in array */
*index++ = i; /* using pointer notation */
free( array ); /* deallocates array */
}
else
{ /* Out of storage */
perror( "Error: out of storage" );
abort();
}
}