😸

[C] free 関数

に公開

機能

動的メモリ領域を解放する標準関数[1]

使用例

メモリを解放しました と表示する

\n は改行を表す エスケープシーケンス[2]

コード

#include <stdlib.h>
#include <stdio.h>
int* ptr = malloc(sizeof(int));
free(ptr);
printf("メモリを解放しました\n");
全文
#include <stdio.h>
#include <stdlib.h>
void main() {
    int* ptr = malloc(sizeof(int));
    free(ptr);
    printf("メモリを解放しました\n");
}

実行結果

メモリを解放しました

値=10 を変数から表示し、解放する

コード

#include <stdlib.h>
#include <stdio.h>
int* ptr = malloc(sizeof(int));
*ptr = 10;
printf("値=%d\n", *ptr);
free(ptr);
全文
#include <stdio.h>
#include <stdlib.h>
void main() {
    int* ptr = malloc(sizeof(int));
    *ptr = 10;
    printf("値=%d\n", *ptr);
    free(ptr);
}

実行結果

値=10
脚注
  1. mallocやcallocなどで確保したメモリを再び使えるように返す処理。メモリリーク防止に重要。 ↩︎

  2. 改行やタブなど、画面に表示されない制御文字のこと。 ↩︎

Discussion