C 언어 동적 메모리 관리: calloc, malloc, free 완벽 이해
이 장에서는 C 언어의 동적 메모리 관리를 설명합니다. C 프로그래밍 언어는 메모리 할당과 관리를 위한 여러 함수를 제공하며, 이 함수들은 <stdlib.h> 헤더 파일에 있습니다.
| 번호 |
함수 및 설명 |
| 1 |
void *calloc(int num, int size); 크기가 size 바이트인 num개의 요소로 구성된 배열을 할당합니다. |
| 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];
하지만 저장해야 할 텍스트의 길이를 알 수 없는 상황을 생각해 보세요. 예를 들어, 어떤 주제에 대한 자세한 설명을 저장해야 한다고 가정해 보겠습니다. 여기서는 필요한 메모리 크기를 정의하지 않고 문자 포인터를 정의한 뒤, 나중에 요구사항에 따라 아래 예제처럼 메모리를 할당할 수 있습니다.
Live Demo
#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
같은 프로그램을 calloc()을 사용하여 작성할 수도 있습니다. malloc을 calloc으로만 바꾸면 됩니다.
calloc(200, sizeof(char));
이처럼 배열과 달리 한 번 크기를 정의하면 바꿀 수 없는 배열과 달리, 메모리 할당 시 원하는 크기 값을 전달하여 완전히 제어할 수 있습니다.
메모리 크기 조정 및 해제
프로그램이 종료되면 운영체제가 프로그램이 할당한 모든 메모리를 자동으로 해제하지만, 더 이상 메모리가 필요하지 않을 때 free() 함수를 호출하여 메모리를 해제하는 것이 좋은 관행입니다.
또는 realloc() 함수를 호출하여 할당된 메모리 블록의 크기를 늘리거나 줄일 수 있습니다. 위 프로그램을 다시 확인하고 realloc()과 free() 함수를 사용하는지 살펴보겠습니다.
Live Demo
#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() 함수가 에러를 발생시킵니다.