logo

malloc(), calloc(), free() 및 realloc()을 사용한 C의 동적 메모리 할당

C는 구조화된 언어이기 때문에 프로그래밍에 대한 몇 가지 고정된 규칙이 있습니다. 그중 하나에는 배열 크기 변경이 포함됩니다. 배열은 인접한 메모리 위치에 저장된 항목의 모음입니다.

배열



보시다시피 위 배열의 길이(크기)는 9입니다. 그런데 이 길이(크기)를 변경해야 하는 요구 사항이 있는 경우 어떻게 될까요? 예를 들어,

  • 이 배열에 5개의 요소만 입력해야 하는 상황이 있는 경우. 이 경우 나머지 4개의 인덱스는 이 배열의 메모리를 낭비하고 있습니다. 그래서 배열의 길이(크기)를 9에서 5로 줄여야 한다는 요구사항이 있습니다.
  • 다른 상황을 생각해보십시오. 여기에는 9개의 인덱스가 모두 채워진 9개의 요소 배열이 있습니다. 하지만 이 배열에는 3개의 요소를 더 입력해야 합니다. 이 경우 3개의 인덱스가 더 필요합니다. 따라서 배열의 길이(크기)를 9에서 12로 변경해야 합니다.

이 절차를 다음과 같이 지칭합니다. C의 동적 메모리 할당 .
그러므로 C 동적 메모리 할당 런타임 중에 데이터 구조(예: 배열)의 크기가 변경되는 프로시저로 정의할 수 있습니다.
C는 이러한 작업을 수행하기 위한 몇 가지 기능을 제공합니다. C에서 제공하는 4개의 라이브러리 함수가 아래에 정의되어 있습니다. C 프로그래밍에서 동적 메모리 할당을 용이하게 하는 헤더 파일입니다. 그들은:

  1. malloc()
  2. 콜록()
  3. 무료()
  4. 재 할당()

각각에 대해 더 자세히 살펴보겠습니다.



C malloc() 메소드

그만큼 malloc 또는 메모리 할당 C의 메소드는 지정된 크기의 단일 대형 메모리 블록을 동적으로 할당하는 데 사용됩니다. 이는 모든 형식의 포인터로 캐스팅될 수 있는 void 유형의 포인터를 반환합니다. 실행 시 메모리를 초기화하지 않으므로 초기에는 기본 가비지 값으로 각 블록을 초기화했습니다.

C의 malloc() 구문

ptr = (cast-type*) malloc(byte-size)   For Example:>

ptr = (int*) malloc(100 * sizeof(int));
int의 크기가 4바이트이므로 이 명령문은 400바이트의 메모리를 할당합니다. 그리고 포인터 ptr은 할당된 메모리의 첫 번째 바이트의 주소를 보유합니다.



공간이 부족하면 할당이 실패하고 NULL 포인터를 반환합니다.

C의 malloc() 예




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >printf>(>'Enter number of elements:'>);> >scanf>(>'%d'>,&n);> >printf>(>'Entered number of elements: %d '>, n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

>

>

산출

Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>

C calloc() 메소드

  1. 콜록 또는 연속 할당 C의 메소드는 지정된 유형의 지정된 수의 메모리 블록을 동적으로 할당하는 데 사용됩니다. 이는 malloc()과 매우 유사하지만 두 가지 다른 점이 있으며 다음과 같습니다.
  2. 각 블록을 기본값 '0'으로 초기화합니다.
  3. malloc()과 비교하여 두 개의 매개변수 또는 인수가 있습니다.

C의 calloc() 구문

ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>

예를 들어:

ptr = (float*) calloc(25, sizeof(float));
이 명령문은 각각 float 크기의 25개 요소에 대해 메모리에 연속 공간을 할당합니다.

공간이 부족하면 할당이 실패하고 NULL 포인터를 반환합니다.

C의 calloc() 예




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d '>, n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by calloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }>

>

>

산출

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>

C free() 메소드

무료 C의 메소드는 동적으로 사용됩니다. 할당 해제 기억. malloc() 및 calloc() 함수를 사용하여 할당된 메모리는 자체적으로 할당 해제되지 않습니다. 따라서 동적 메모리 할당이 발생할 때마다 free() 메서드가 사용됩니다. 메모리를 해제하여 메모리 낭비를 줄이는 데 도움이 됩니다.

C의 free() 구문

free(ptr);>

슬로카 메타

C의 free() 예




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int> *ptr, *ptr1;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d '>, n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Dynamically allocate memory using calloc()> >ptr1 = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL || ptr1 == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc. '>);> >// Free the memory> >free>(ptr);> >printf>(>'Malloc Memory successfully freed. '>);> >// Memory has been successfully allocated> >printf>(>' Memory successfully allocated using calloc. '>);> >// Free the memory> >free>(ptr1);> >printf>(>'Calloc Memory successfully freed. '>);> >}> >return> 0;> }>

>

>

산출

Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>

C realloc() 메소드

재할당 또는 재할당 C의 메소드는 이전에 할당된 메모리의 메모리 할당을 동적으로 변경하는 데 사용됩니다. 즉, 이전에 malloc이나 calloc을 사용하여 할당한 메모리가 부족할 경우 realloc을 사용하여 해결할 수 있습니다. 동적으로 메모리를 재할당 . 메모리 재할당은 이미 존재하는 값을 유지하고 새 블록은 기본 가비지 값으로 초기화됩니다.

C의 realloc() 구문

ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

공간이 부족하면 할당이 실패하고 NULL 포인터를 반환합니다.

C의 realloc() 예




#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d '>, n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated. '>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc. '>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } // Get the new size for the array n = 10; printf(' Enter the new size of the array: %d ', n); // Dynamically re-allocate memory using realloc() ptr = (int*)realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf('Memory successfully re-allocated using realloc. '); // Get the new elements of the array for (i = 5; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } free(ptr); } return 0; }>

>

>

산출

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,>

realloc() 메소드의 또 다른 예는 다음과 같습니다.

자바 객체




#include> #include> int> main()> {> >int> index = 0, i = 0, n,> >*marks;>// this marks pointer hold the base address> >// of the block created> >int> ans;> >marks = (>int>*)>malloc>(>sizeof>(> >int>));>// dynamically allocate memory using malloc> >// check if the memory is successfully allocated by> >// malloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >// memory has successfully allocated> >printf>(>'Memory has been successfully allocated by '> >'using malloc '>);> >printf>(>' marks = %pc '>,> >marks);>// print the base or beginning> >// address of allocated memory> >do> {> >printf>(>' Enter Marks '>);> >scanf>(>'%d'>, &marks[index]);>// Get the marks> >printf>(>'would you like to add more(1/0): '>);> >scanf>(>'%d'>, &ans);> >if> (ans == 1) {> >index++;> >marks = (>int>*)>realloc>(> >marks,> >(index + 1)> >*>sizeof>(> >int>));>// Dynamically reallocate> >// memory by using realloc> >// check if the memory is successfully> >// allocated by realloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >printf>(>'Memory has been successfully '> >'reallocated using realloc: '>);> >printf>(> >' base address of marks are:%pc'>,> >marks);>////print the base or> >///beginning address of> >///allocated memory> >}> >}> >}>while> (ans == 1);> >// print the marks of the students> >for> (i = 0; i <= index; i++) {> >printf>(>'marks of students %d are: %d '>, i,> >marks[i]);> >}> >free>(marks);> >}> >return> 0;> }>

>

>

산출: