標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
ISO C |
両方 |
#include <stdlib.h>
void free(void *ptr);
ptr で指定されるストレージのブロックを解放します。ptr 変数は、calloc()、 malloc()、realloc() または strdup() の呼び出し によって以前に確保されたブロックを指します。解放されるバイト数は、ストレージのブロックを確保 (realloc() の場合は 再割り振り) するときに指定したバイト数です。ptr が NULL の場合は、free() は単に戻るだけで、 何も解放しません。 ptr は値で渡されるので、free() は、ptr が指すメモリー を解放した後で、ptr を NULL に設定しません。
C++ の特殊な動作: C++ では、C++ の新しいキーワードを使用して割り振られた項目に対して free() を使用することはできません。
free() は値を戻しません。
/* This example illustrates the use of calloc() to allocate storage for x
array elements and then calls free() to free them.
*/
#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 = (long *)calloc( num, sizeof( long ))) != NULL )
{
⋮ /* do something with the array */
free( array ); /* deallocates array */
}
else
{ /* Out of storage */
printf( "Error: out of storage¥n" );
abort();
}
}