C 라이브러리 메모리 할당 함수 void *malloc(size_t size)는 요청된 메모리를 할당하고 이에 대한 포인터를 반환합니다.
메모리 할당 기능
메모리는 아래에 설명된 대로 두 가지 방법으로 할당할 수 있습니다. -

메모리는 컴파일 시간에 할당되면 실행 중에 변경할 수 없습니다. 메모리가 부족하거나 낭비되는 문제가 있습니다.
솔루션은 프로그램 실행 중 사용자의 요구 사항에 따라 동적으로 메모리를 생성하는 것입니다.
동적 메모리 관리에 사용되는 표준 라이브러리 함수는 다음과 같습니다. -
- malloc( )
- 호출()
- 실제 할당( )
- 무료( )
Malloc() 함수
이 함수는 런타임에 메모리 블록을 바이트 단위로 할당하는 데 사용됩니다. 할당된 메모리의 기본 주소를 가리키는 void 포인터를 반환합니다.
malloc()의 구문은 다음과 같습니다 -
void *malloc (size in bytes)
예시 1
다음은 malloc() 함수의 사용 예입니다.
int *ptr; ptr = (int * ) malloc (1000); int *ptr; ptr = (int * ) malloc (n * sizeof (int));
참고 - 메모리가 비어 있지 않으면 NULL을 반환합니다.
예시 프로그램
다음은 동적 메모리 할당 기능을 보여주는 C 프로그램 - malloc()입니다.
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointer//
int numofele,i;
int *p;
//Reading elements as I/p//
printf("Enter the number of elements in the array: ");
scanf("%d",&numofele);
//Declaring malloc function//
p = (int *)malloc(numofele * (sizeof(int)));
//Reading elements into array of pointers//
for(i=0;i<numofele;i++){
p[i]=i+1;
printf("Element %d of array is : %d\n",i,p[i]);
}
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
Enter the number of elements in the array: 4 Element 0 of array is : 1 Element 1 of array is : 2 Element 2 of array is : 3 Element 3 of array is : 4
예시 2
다음은 동적 메모리 할당 기능을 사용하여 요소를 표시하는 C 프로그램입니다. -
처음 5개 블록은 비어 있어야 하고, 두 번째 5개 블록에는 논리가 있어야 합니다.
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointers,sum//
int numofe,i,sum=0;
int *p;
//Reading number of elements from user//
printf("Enter the number of elements : ");
scanf("%d",&numofe);
//Calling malloc() function//
p=(int *)malloc(numofe*sizeof(int));
/*Printing O/p -
We have to use if statement because we have to check if memory
has been successfully allocated/reserved or not*/
if (p==NULL){
printf("Memory not available");
exit(0);
}
//Printing elements//
printf("Enter the elements : \n");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("\nThe sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("\nDisplaying the cleared out memory location : \n");
for(i=0;i<numofe;i++){
printf("%d\n",p[i]);//Garbage values will be displayed//
}
} 출력
위의 프로그램이 실행되면 다음과 같은 결과가 생성됩니다 -
Enter the number of elements : 5 Enter the elements : 12 10 24 45 67 The sum of elements is 158 Displaying the cleared out memory location : 7804032 0 7799120 0 67