Latest web development tutorials

C 메모리 관리

이 장에서는 C 동적 메모리 관리를 설명합니다. 메모리의 할당 및 관리를위한 C 언어가 여러 가지 기능을 제공한다. 이 기능은<인 stdlib.h> 헤더 파일에서 찾을 수 있습니다.

序号函数和描述
1void *calloc(int num, int size);
该函数分配一个带有num个元素的数组,每个元素的大小为size字节。
2void free(void *address);
该函数释放 address 所指向的h内存块。
3void *malloc(int num);
该函数分配一个num字节的数组,并把它们进行初始化。
4void *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 );
}

상기 코드는 컴파일되고 실행될 때, 다음과 같은 결과를

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

위의 프로그램은 다음과 같이 단지의 malloc은 calloc를 교체해야,작성은 calloc ()를 사용할 수 있습니다 :

calloc(200, sizeof(char));

메모리의 동적 할당, 당신은 임의의 값의 크기를 완벽하게 제어 할 수있을 때 전달 될 수 있습니다. 이 정의되면 이러한 미리 정의 된 어레이의 크기는 크기를 변경할 수 없다.

메모리 크기 및 사용 가능한 메모리를 다시 조정

프로그램이 종료하면 운영 체제가 자동으로 프로그램에 할당 된 모든 메모리를 해제하지만, 메모리를 필요가 없습니다, 당신은 무료로 메모리에() 무료 함수를 호출해야하는 것이 좋습니다.

다른 방법으로는 할당 된 메모리 블록의 크기를 증가 또는 감소 함수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);
}

상기 코드는 컴파일되고 실행될 때, 다음과 같은 결과를

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

당신은 여분의 메모리, strcat와 () 함수 부족으로 저장된 설명 사용할 수있는 메모리의 오류가 발생 재 할당을 시도 할 수 없습니다.