Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ mallocとfree | ポインタ
C基礎

bookmallocとfree

メニューを表示するにはスワイプしてください

これらの関数を使用することで、コンパイル時ではなくプログラム実行時に新しいオブジェクトを作成でき、動的メモリ割り当てが可能となる。

malloc()

以前は、データ用のメモリを割り当てる際、単純に次のように宣言していた:

int x;

現在は、malloc()関数を使うことで動的にメモリを割り当てることができる:

int* pX = (int*)malloc(4);

malloc()関数は、割り当てるバイト数を引数として必要とする。必要なバイト数が不明でも、格納するデータ型が分かっていれば、次のように式を調整できる:

int* pX = (int*)malloc(sizeof(int));

次は何か? malloc()関数の結果をポインタに代入している点に注目。これは、malloc()アドレスを返すことを意味する。

接頭辞 (int*)明示的キャスト。希望する型を手動で指定。 例:

double x = 3.14;
int y = (int)x;   // `y` = 3
Main.c

Main.c

copy
1234567891011
#include <stdio.h> #include <stdlib.h> // new header file! int main() { int* pX = (int*)malloc(sizeof(int)); printf("Address of allocated memory: %p\n", pX); return 0; }

注意

ヘッダーファイル stdlib.h を必ずインクルード。malloc() 関数のプロトタイプが含まれている。

malloc() 関数が返すアドレスにデータを格納するには、間接参照演算子を使用。

Main.c

Main.c

copy
123456789101112
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf(" Value %d at address %p\n", *pX, pX); return 0; }

メモリを解放することは可能ですか? – はい、ただし malloc() や類似の関数で確保されたメモリのみ可能です。

free()

この関数はポインタとともに使用。上記の例を拡張して説明:

Main.c

Main.c

copy
1234567891011121314151617
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf(" Value %d at address %p\n", *pX, pX); free(pX); printf("After `free()` value %d at address %p\n", *pX, pX); return 0; }

興味深いことに、ポインタを「削除」した後でも、そのポインタ自体は機能しますが、関連付けられたメモリ領域に格納されている値は壊れてしまいます。

このため、使用中のメモリセルが信頼できないデータを保持する問題が発生します。これらのポインタを防ぐために、使用済みのポインタはNULLにリセットする必要があります。

Main.c

Main.c

copy
1234567891011121314151617
#include <stdio.h> #include <stdlib.h> int main() { int* pX = (int*)malloc(sizeof(int)); *pX = 100; printf("Value %d at address %p\n", *pX, pX); free(pX); pX = NULL; return 0; }

メモリを解放した後にポインタをNULLに設定することで、そのポインタがもはや有効なメモリアドレスを参照していないことを明確に示すことができます。

ポインタを使用する前には必ずNULLかどうかを確認し、無効または既に割り当てられたメモリにアクセスしないようにしてください。

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 6.  4
some-alt