Blog/JAVA기반 스마트웹 개발2021

프로그래밍 언어 활용 part 2 - 동적 메모리

고구마달랭이 2021. 8. 9. 20:56

동적 메모리

학습내용 학습목표
▪ 동적 메모리 이해
▪ 동적 메모리 활용
▪ 동적 메모리의 기본 개념을 파악하고 용도를 설명할 수 있다.
▪ 동적으로 메모리 할당이 필요한 작업에 적용할 수 있다.

동적 메모리 이해

 

1. 개요

데이터의 개수를 미리 알 수 없을 때 사용

처리 대상 데이터가 유동적일 때, 특히 변동 폭이 큰 경우

 

 

2. 라이브러리 함수

[1] 종류

(1) 헤더파일 stdlib.h

 

[2] malloc()

 

[3] free()

 

[4] calloc()

 

[5] realloc()

 

 


 

동적 메모리 활용


1. 함수 기초

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

int main()
{
	char *a;
	int size;
	scanf(“%d”, &size);
    
	a = malloc( sizeof(char)*size );
 	strcpy(a,“hi”);
    
	printf(“문자수 : %d 문자열 : \n”, strlen(a), a );
	free(a);
	return 0;
}
#include <stdio.h>
#include <stdlib.h>

int main()
{
	int *a;
	int size;
	scanf(“%d”, &size);
	a = (int *) calloc( sizeof(int), size );

free(a)
return 0;
}

 

2. 함수 활용

 

Q. 문자열을 입력받고 하나의 동적 메모리에 계속 붙여서 Q 저장하는 프로그램을 작성하시오. (“end” 입력 시 입력 종료)

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

int main()
{
   char *a, str[20];
   a = (char *)calloc(1,1);
   if (a == NULL) printf(“Fail Allocation”);
	while(1){
		 gets(str);
 		if( !strcmp(str,“end”) )
 		break;
 		a = (char *)realloc(a,strlen(str)+1);
		 strcat(a,str);
 }
 printf(“\n%s”, a);
 
 free(a);
 return 0;
}

 

 


 

 

학습정리

 

1. 동적 메모리 이해

동적 할당은 실행 시에 할당되는 메모리임

동적 할당은 힙 영역에 할당함

동적 할당은 실행 시 크기가 정해지는 데이터 처리에 효과적임

동적 할당된 공간은 프로그래머가 해제해야 함

 

2. 동적 메모리 활용

malloc, calloc은 동적으로 메모리를 할당하는 라이브러리 함수임

calloc은 동적 할당 후 0으로 초기화

free는 동적 할당된 메모리를 해제함

▪ realloc은 동적 메모리의 크기를 변경하여 할당하는 것이 가능함