malloc, calloc, reallocで取得した動的メモリを解放するには、free関数を使用します。
取得したメモリを使い終わったら必ずfreeするようにしましょう。
以下にmalloc, freeを使用したC言語サンプルソースを記します。
以下にfree関数の書式等を記します。
#include <stdlib.h>
void free(void *ptr);
以下にfreeを使用したC言語サンプルソースを記します。 &ref(): File not found: "free.c" at page "メモリ/malloc,calloc,reallocで取得したメモリを解放する・free"; (改行コードLF)
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main(void) { char *src = "HELLO WORLD!\n"; char *p = NULL; int i; p = malloc(strlen(src)+1); if (p == NULL) { perror("malloc() error!"); exit(EXIT_FAILURE); } strcpy(p,src); printf("%s", p); if (p != NULL) { free(p); p = NULL; } return 0; }
以下にコンパイルし実行した結果を記します。
$ gcc free.c -o free $ ./free HELLO WORLD!
以上、malloc, freeのサンプルソースでした。
c-btm.html is not found or not readable.