Loose-Info.com
Last Update 2012/07/05
TOP - C言語 - stdlib.h - realloc()

malloc()などで確保したメモリを、指定したサイズに変更します。

 戻り値1  = realloc(  引数1  ,  引数2  )

戻り値1 :
void *
成功
確保されたメモリを参照するポインタ
失敗
NULL
引数1 :
void *
サイズ変更するメモリ領域へのポインタ
このポインタがNULLの場合、malloc()と同等となります。
引数2 :
size_t
変更後のサイズ

(例)
#include <stdio.h> #include <stdlib.h> int main() { int i; char *pc = (char *)malloc(15); if (pc == NULL) { printf("確保失敗\n"); return 0; } for (i=0; i<10; i++) { *(pc+i) = i + 0x30; } *(pc+i) = '\0'; for (i=0; i<10; i++) { printf("[%d] : %c\n", i, *(pc+i)); } printf("%s\n\n", pc); char *pc2 = (char *)realloc(pc, 30); if (pc2 == NULL) { printf("realloc失敗\n"); free(pc); return 0; } for (i=10; i<20; i++) { *(pc2+i) = i + 0x30; } *(pc2+i) = '\0'; for (i=0; i<20; i++) { printf("[%02d] : %c\n", i, *(pc2+i)); } printf("%s\n", pc2); free(pc2); return 0; }

実行結果
[0] : 0 [1] : 1 [2] : 2 [3] : 3 [4] : 4 [5] : 5 [6] : 6 [7] : 7 [8] : 8 [9] : 9 0123456789 [00] : 0 [01] : 1 [02] : 2 [03] : 3 [04] : 4 [05] : 5 [06] : 6 [07] : 7 [08] : 8 [09] : 9 [10] : : [11] : ; [12] : < [13] : = [14] : > [15] : ? [16] : @ [17] : A [18] : B [19] : C 0123456789:;<=>?@ABC