#navi(contents-page-name): No such page: メモリ

malloc,calloc,reallocで取得したメモリを解放する・free

malloc, calloc, reallocで取得した動的メモリを解放するには、free関数を使用します。
取得したメモリを使い終わったら必ずfreeするようにしましょう。
以下にmalloc, freeを使用したC言語サンプルソースを記します。

c-top.html is not found or not readable.

関連記事

free関数の書式など

以下にfree関数の書式等を記します。

freeを使用したサンプルソース

以下に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.

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS