C•動的メモリ
C言語の動的メモリ管理:malloc、calloc、realloc、free
ヒープ上の手動メモリ管理、確保失敗(NULL)のチェック、メモリリークの防止方法を学びます。
構文
int* arr = (int*)malloc(n * sizeof(int));
free(arr);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| malloc(size) | Function | ヒープ上に未初期化のバイトブロックを確保します。 |
| free(ptr) | Function | 確保したヒープメモリをOSへ返却します。 |
そのまま実行できるコード例
Compilra で実行可能C をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int capacity = 3;
// Allocate buffer on heap
int* buffer = (int*)malloc(capacity * sizeof(int));
if (buffer == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
buffer[0] = 100;
buffer[1] = 200;
buffer[2] = 300;
printf("Initial Heap Buffer:\n");
for (int i = 0; i < capacity; i++) {
printf(" buffer[%d] = %d\n", i, buffer[i]);
}
// Free allocated memory
free(buffer);
buffer = NULL; // Prevent dangling pointer
printf("Heap memory freed safely.\n");
return 0;
}期待される出力:
Initial Heap Buffer: buffer[0] = 100 buffer[1] = 200 buffer[2] = 300 Heap memory freed safely.
動作のしくみ: ステップ解説
- 7〜13行目: malloc でヒープ上に 3 * sizeof(int) バイトを確保し NULL かどうか確認します。
- 15〜22行目: ヒープバッファへ値を書き込み、読み取ります。
- 25〜26行目: free(buffer) でメモリを解放し、ポインタを NULL に設定します。
重要ポイント
- malloc はメモリを初期化しませんが、calloc は確保した全バイトをゼロクリアします。
- メモリリークを防ぐため、すべての malloc 呼び出しには対応する free 呼び出しが必要です。
- 解放後使用(use-after-free)バグを防ぐため、解放後は必ずポインタに NULL を代入しましょう。
よくある間違い: free() を呼ばずにポインタ参照を失いメモリリークを起こすこと
確保したメモリを解放する前にポインタを上書きすると、そのRAM領域は永続的にリークします。
❌ 誤り
int* p = malloc(100); p = malloc(200); // First 100 bytes are leaked forever!
✅ 正しい例
int* p = malloc(100); free(p); p = malloc(200); free(p);