동적 메모리 할당이란 프로그램이 실행 도중에 메모리를 할당 받는 것을 말합니다.
프로그램에서는 필요한 만큼의 메모리
를 시스템으로부터 할당을 받아 사용
하고,
사용이 끝나면 시스템 메모리에 반납
합니다.
필요한 만큼만 할당을 받고 또 필요한 때에 사용하고 반납해 메모리를 효율적으로 사용할 수 있습니다.
동적 메모리는 malloc()
계열의 라이브러리 함수를 사용하여 할당 받아 사용할 수 있습니다.
동적 메모리의 사용이 끝나면 반드시 해당 메모리 영역을 명시적으로 반납 해주어야합니다.
#include <stdio.h>
#include <stdlib.h> // 동적 메모리를 사용하기 위해 필요한 라이브러리
int main (void){
int *pi; // Pointer Integer
pi = (int *)malloc(sizeof(int)) // malloc = 메모리를 할당해라
if(pi == NULL)
{
printf("동적 메모리 할당에 실패\n");
exit(1);
}
*pi = 100;
printf("%d\n", *pi)
/* 동적 메모리 사용한 이후에는 무조건 해당 메모리를 반환합니다. */
free(pi); // pi가 가진 메모리를 해제(free) 해준다.
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main (void){
char *pc = NULL;
int i = 0;
pc = (char *)malloc(100 * sizeof(char));
if(pc == NULL)
{
printf("동적 메모리 할당에 실패\n");
exit(1);
}
for(i = 0; i < 26; i++)
{
*(pc + i) = 'a' + i; // pc가 가르키는 포인터를 1씩 증가시키며 알파벳 소문자를 삽입합니다.
}
*(pc + i) = 0; // 아스키 코드에서 0은 NULL을 의미합니다.
printf("%s"\n, pc); // abcdedefghijklmnopqrstuvwxyz
free(pc); // 동적 메모리 해제
return 0;
}
위의 코드가 출력되면 a
의 아스키 코드 97
이고 + 1씩 더하면 b(98),c(99) ... 26번째의 z까지 나오게 됩니다.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *pi, i;
pi = (int *)malloc(5 * sizeof(int));
if(pi == NULL)
{
printf("동적 메모리 할당에 실패\n");
exit(1);
}
pi[0] = 100;
pi[1] = 200;
pi[2] = 300;
pi[3] = 400;
pi[4] = 500;
for(i = 0; i < 5; i++)
{
printf("%d\n", *(pi + 1));
}
free(pi); // 동적 메모리 해제
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct Book
{
int number;
char title[100];
};
void showBook(struct Book *p, int n)
{
int i;
for(i = 0; i < n; i++)
{
printf("번호 %d : %s\n", (p+i)->number, p+i)->title);
}
}
int main(void)
{
struct Book *p;
p = (struct Book *)malloc(2 * sizeof(struct Book));
if(p == NULL)
{
printf("동적 메모리 할당에 실패\n");
exit(1);
}
p->number = 1;
strcpy(p->title, "C programming");
(p + 1)->number = 2;
strcpy((p + 1)->title, "Data Structure");
showBook(p, 2);
free(p); // 동적 메모리 해제
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i, x, y;
int** pptr = (int**)malloc(sizeof(int*) * 8); // x배열
for(i = 0; i < 8; i++)
{
*(pptr + i) = (int *)malloc(sizeof(int) * 6); //x배열 내의 y배열
}
for(y = 0; y < 8; y++)
{
for(x = 0; x < 6; x++)
{
*(*(pptr + y) + x) = 6 * y + x; // 값 초기화
}
}
for(y = 0; y < 8; y++)
{
for(x = 0; x < 6; x++)
{
printf("%3d", *(*(pptr + y) + x)); // 값 출력
}
printf("\n");
}
for(y = 0; y < 8; y++)
{
free(*(pptr + y)); // 동적 메모리 해제
}
return 0;
}