다음과 같은 프로그램을 작성할 수 있다.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("Usage : ./memory-user <memory size in megabytes>");
exit(0);
}
unsigned long long mem_size;
int mem_size_mb;
char* buf;
mem_size_mb = atoi(*(argv + 1));
mem_size = mem_size_mb * 1024 * 1024;
mem_size = mem_size / sizeof(char);
buf = calloc(mem_size, sizeof(char));
int ctr = 0;
char str[] = {'m', 'b', 'c', 'j', 't', '6', '3'};
while(1)
{
for(int i = 0; i < mem_size; i++)
{
*(buf + i) = str[ctr];
ctr++;
if(ctr == 7)
{
ctr = 0;
}
}
}
return 0;
}
프로그램 실행 인자로 사용할 메모리의 크기를 받는다.
while문 내에서 정해진 크기의 동적 할당된 메모리 전체에 계속해서 접근하고 있다.
이제 이를 컴파일해 실행하자.
<aside> 🕊️ gcc -o memory-user memory-user.c
</aside>
실행 전후에 free -m 명령어를 통해 남아 있는 메모리를 megabyte 단위로 출력한다고 생각해 보자.

man free 명령어로 free의 대략적인 설명을 확인한 결과는 위와 같다.

실제 결과는 위와 같다.