0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語 free関数を使う際の注意点

Posted at

はじめに

42tokyoの生徒です。mallocを使う時に、必ず行うfreeですが、freeについてあまり知らなかったので、調べてみたところ、いくつか注意点があるとのことだったので備忘のためにまとめます。

free関数の定義

  void free(void *ptr);

free() 関数は、ptr が指すメモリ割り当てを解放する。ptr が NULL ポインタの場合、操作は行われない。※man freeの内容を翻訳

free関数を使う際の注意点

①二重解放はしない

NG例
free(ptr);
// これは誤り!
free(ptr); // 二重解放となりクラッシュの原因となる

②NULLポインタの解放はしない

NG例
int *ptr = NULL;
// これは誤り!
free(ptr); // NULLポインタの解放はクラッシュの原因となる

③動的に確保したメモリ以外を解放しない

NG例
int a = 10; // スタック領域に確保された変数
// これは誤り!
free(&a);  // スタック領域のメモリを解放しようとするとエラーになる

④メモリの先頭アドレス以外は解放しない

NG例
int *arr = (int *)malloc(10 * sizeof(int));
int *ptr = arr + 3;  // arrの4番目の要素へのポインタ

// これは誤り!
free(ptr);  // 配列の一部しか解放できず、メモリリークが発生する
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?