reallocとは?
The realloc() function tries to change the size of the allocation pointed to by ptr to size, and returns ptr. If there is not enough room to enlarge the
memory allocation pointed to by ptr, realloc() creates a new allocation, copies as much of the old data pointed to by ptr as will fit to the new allocation,
frees the old allocation, and returns a pointer to the allocated memory. If ptr is NULL, realloc() is identical to a call to malloc() for size bytes. If
size is zero and ptr is not NULL, a new, minimum sized object is allocated and the original object is freed. When extending a region allocated with
calloc(3), realloc(3) does not guarantee that the additional memory is also zero-filled.
void *
realloc(void *ptr, size_t size);
reallocは、**「今持っているメモリの領域(箱)のサイズを変更する」**ための関数。
reallocが成功すれば、必ず 「古いデータがコピーされた、新しいサイズの領域」 を指す。
使用例
例)現在のメモリにはhelloが入っている。続きにworldを入れたいがhelloの分しかメモリがない。
→そうだ!メモリを拡張しよう!
reallocは新しいポインタで受け取る。
// よい例
new_memory_ptr = realloc(ptr, 新しいサイズ);
// ダメな例(危険!)
ptr = realloc(ptr, 新しいサイズ);
ダメな理由
→もしreallocが メモリ不足で失敗すると、NULLが返ってくる。
するとptrがNULLに上書きされてしまい、元々持っていたメモリの場所がわからなくなってしまう(メモリリーク)。
reallocの安全な使い方
1. 一旦、新しい場所を仮の変数 new_memory_ptr で受け取る。
new_memory_ptr = realloc(ptr, 新しいサイズ);
2. 成功したかチェックする。
if (!new_memory_ptr) { /* 失敗時の処理: 元のptrをfreeして終了 */ }
3. 成功を確認してから、正式なポインタを更新する。
ptr = new_memory_ptr;