標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
ISO C |
両方 |
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
直前に予約されていたストレージ・ブロックのサイズを変更します。ptr 引数は、ブロックの先頭を指しています。size 引数は、ブロックの新しいサイズ (バイト単位) を指定しています。ブロックの内容は、新旧サイズの短い方に達するまでは変更されません。
ptr が NULL の場合には、realloc() は size バイトの ストレージのブロックを予約します。これによって、各エレメントのすべてのビットが初期値 0 にされるわけではありません。
size が 0 になっていて、ptr が NULL でない場合には、ptr によって指されたストレージが解放され、NULL が戻されます。
malloc()、calloc()、または realloc() によって以前作成された ptr を指していないポインターを使って realloc() を実行した場合、または既に解放されたストレージに ptr を渡した場合、未定義の動作 (通常は例外) が発生します。
ストレージを大きくする要求の場合、拡張部分の内容は 未定義であり、0 になっているという保証はありません。
戻された値が指しているストレージは、不特定型のオブジェクトのストレージに位置合わせされます。z/OS® XL C の場合に限り、4 K 境界合わせを要求した場合は、__4kmalc() 関数を使用する必要があります。(この関数は、独立型システム・プログラミング C (SPC) 機能アプリケーションの C アプリケーションでのみ使用できます。) システム・プログラミング C (SPC) 環境固有のライブラリー関数については、「z/OS XL C/C++ プログラミング・ガイド」で説明しています。
realloc() のヒープ・ストレージ不足の原因を調査するためには、「」を参照してください。z/OS Language Environment プログラミング・リファレンス
C++ の特殊な動作: C++ のキーワード new と delete は、calloc()、free()、 malloc()、または realloc() と相互操作可能ではありま せん。
正常に実行された場合、realloc() は、再度割り振られたストレージ・ブロックを指すポインターを戻します。ブロックの保管場所は、移動される可能性があります。したがって、戻り値は必ずしも realloc() に対する ptr 引数と同じであるとは限りません。
⁄* CELEBR06
This example allocates storage for the prompted size of array
and then uses &realloc. to reallocate the block to hold the
new size of the array.
The contents of the array are printed after each allocation.
*⁄
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
long * array; ⁄* start of the array *⁄
long * ptr; ⁄* pointer to array *⁄
int i; ⁄* index variable *⁄
int num1, num2; ⁄* number of entries of the array *⁄
void print_array( long *ptr_array, int size);
printf( "Enter the size of the array¥n" );
scanf( "%i", &num1 );
⁄* allocate num1 entries using malloc() *⁄
if ( (array = (long *)malloc( num1 * sizeof( long ))) != NULL ) {
for ( ptr = array, i = 0; i < num1 ; ++i ) ⁄* assign values *⁄
*ptr++ = i;
print_array( array, num1 );
printf("¥n");
}
else { ⁄* malloc error *⁄
printf( "Out of storage¥n" );
abort();
}
⁄* Change the size of the array ... *⁄
printf( "Enter the size of the new array¥n" );
scanf( "%i", &num2);
if ( (array = (long *)realloc( array, num2* sizeof( long ))) != NULL )
{
for ( ptr = array + num1, i = num1; i <= num2; ++i )
*ptr++ = i + 2000; ⁄* assign values to new elements *⁄
print_array( array, num2 );
}
else { ⁄* realloc error *⁄
printf( "Out of storage¥n" );
abort();
}
}
void print_array( long * ptr_array, int size )
{
int i;
long * index = ptr_array;
printf("The array of size %d is:¥n", size);
for ( i = 0; i < size; ++i ) ⁄* print the array out *⁄
printf( " array[ %i ] = %li¥n", i, ptr_array[i] );
}
Enter the size of the array
The array of size 2 is:
array[ 0 ] = 0
array[ 1 ] = 1
Enter the size of the new array
The array of size 4 is:
array[ 0 ] = 0
array[ 1 ] = 1
array[ 2 ] = 2002
array[ 3 ] = 2003