工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> C言語

C言語動的メモリ管理:calloc、malloc、freeの解説

この章ではC言語の動的メモリ管理を説明します。C言語はメモリ割り当てと管理のための関数をいくつか提供しており、これらは<stdlib.h>ヘッダーファイルにあります。

No.関数と説明
1

void *calloc(int num, int size);

num個の要素からなる配列を割り当て、各要素のサイズはsizeバイト。

2

void free(void *address);

addressで指定されたメモリブロックを解放する。

3

void *malloc(size_t size);

sizeバイトのメモリを割り当て、未初期化のままにする。

4

void *realloc(void *address, int newsize);

メモリをnewsizeまで再割り当て(拡張・縮小)する。

動的メモリ割り当て

プログラミング時に配列サイズがわかっているなら、配列として定義すれば簡単です。例えば、人名を格納するなら最大100文字として:

char name[100];

しかし、格納するテキストの長さが不明な状況、例えば詳細な説明文を格納する場合を考えます。ここでは文字へのポインタを定義し、後で必要に応じてメモリを割り当てます。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    char name[100];
    char *description;
    strcpy(name, "Zara Ali");
    /* 動的にメモリ割り当て */
    description = malloc(200 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(description, "Zara ali a DPS student in class 10th");
    }
    printf("Name = %s\n", name);
    printf("Description: %s\n", description);
    return 0;
}

実行結果:

Name = Zara Ali
Description: Zara ali a DPS student in class 10th

同じプログラムをcalloc()で書くこともできます。mallocをcallocに置き換えるだけです。

calloc(200, sizeof(char));

このように、配列のように一度サイズを決めると変更できないのとは異なり、動的割り当てでは任意のサイズを指定して完全に制御できます。

メモリのリサイズと解放

プログラム終了時、OSがプログラムによって割り当てられたメモリを自動的に解放しますが、メモリが不要になった時点でfree()関数を呼んで明示的に解放するのが良い習慣です。

あるいは、realloc()関数で割り当て済みメモリブロックのサイズを増減できます。前のプログラムを拡張してrealloc()とfree()を使ってみます。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    char name[100];
    char *description;
    strcpy(name, "Zara Ali");
    /* 動的にメモリ割り当て */
    description = malloc(30 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcpy(description, "Zara ali a DPS student.");
    }
    /* より大きな説明文を格納したい */
    description = realloc(description, 100 * sizeof(char));
    if (description == NULL) {
        fprintf(stderr, "Error - unable to allocate required memory\n");
    } else {
        strcat(description, "She is in class 10th");
    }
    printf("Name = %s\n", name);
    printf("Description: %s\n", description);
    /* free()関数でメモリ解放 */
    free(description);
    return 0;
}

実行結果:

Name = Zara Ali
Description: Zara ali a DPS student.She is in class 10th

再割り当てなしで上記例を試すと、strcat()が利用可能メモリ不足でエラーになります。

C言語

  1. 非メカニカルデジタルメモリの理解:SRAM、DRAM、フラッシュ
  2. ROM、PROM、EPROM、EEPROMの理解:設計、プログラミング、識別
  3. マイクロプロセッサ:ストアドプログラムコンピューティングの進化
  4. 2012年資産管理イベント:主要カンファレンス、トレーニング、展示会
  5. 効果的な資産管理のための4つの主要目的
  6. メンテナンス管理の決定版ハンドブック:リーダーのための実践ガイド
  7. C++メモリ管理の極意:newとdeleteのエキスパート活用法
  8. C言語 動的メモリ確保: malloc, calloc, realloc, free をマスターする
  9. C++動的メモリ管理完全解説:スタックとヒープ、new/delete
  10. Javaドキュメンテーションコメント:Javadocとコメントタイプをマスター
  11. Java 10でヒープをNV-DIMMに割り当て:-XX:AllocateHeapAtオプション