free() - ストレージのブロックの解放

標準

標準/拡張機能 C/C++ 依存項目

ISO C
POSIX.1
XPG4
XPG4.2
C99
Single UNIX Specification、バージョン 3

両方  

形式

#include <stdlib.h>

void free(void *ptr);

機能説明

ptr で指定されるストレージのブロックを解放します。ptr 変数は、calloc()、 malloc()、realloc() または strdup() の呼び出し によって以前に確保されたブロックを指します。解放されるバイト数は、ストレージのブロックを確保 (realloc() の場合は 再割り振り) するときに指定したバイト数です。ptr が NULL の場合は、free() は単に戻るだけで、 何も解放しません。 ptr は値で渡されるので、free() は、ptr が指すメモリー を解放した後で、ptr を NULL に設定しません。

この関数は、独立型システム・プログラミング C (SPC) 環境の C アプリケーションでも 使用できます。
注: calloc()、malloc()、realloc()、strdup()、 または既に解放されたストレージによって 割り振られなかったストレージのブロックを解放 しようとすると、その後ストレージを確保するときに影響が生じて、異常終了が 引き起こされることがあります。

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();
  }
}

関連情報