Cprogramming-c-memory-management

提供:Dev Guides
移動先:案内検索

C-メモリ管理

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

Sr.No. Function & Description
1

void *calloc(int num, int size);

この関数は、バイト単位のサイズが size になる num 要素の配列を割り当てます。

2

void free(void *address);

この関数は、アドレスで指定されたメモリブロックのブロックを解放します。

3

void *malloc(int num);

この関数は、 num バイトの配列を割り当て、初期化せずに残します。

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");

  /*allocate memory dynamically*/
   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 );
}

上記のコードをコンパイルして実行すると、次の結果が生成されます。

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

同じプログラムは、 calloc(); を使用して記述できます。次のように、mallocをcallocに置き換える必要があるのは、ただ-

calloc(200, sizeof(char));

したがって、完全に制御でき、サイズを一度定義すると変更できないアレイとは異なり、メモリの割り当て中に任意のサイズ値を渡すことができます。

メモリのサイズ変更と解放

プログラムが出てくると、オペレーティングシステムはプログラムによって割り当てられたすべてのメモリを自動的に解放しますが、メモリが不要になった場合は、* free()*関数を呼び出してそのメモリを解放することをお勧めします。

または、関数* realloc()*を呼び出して、割り当てられたメモリブロックのサイズを増減できます。 上記のプログラムをもう一度確認し、realloc()およびfree()関数を使用してみましょう-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

   char name[100];
   char *description;

   strcpy(name, "Zara Ali");

  /*allocate memory dynamically*/
   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.");
   }

  /*suppose you want to store bigger description*/
   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 );

  /*release memory using free() function*/
   free(description);
}

上記のコードをコンパイルして実行すると、次の結果が生成されます。

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

余分なメモリを再割り当てせずに上記の例を試すことができます。説明に利用可能なメモリがないため、strcat()関数はエラーを返します。