Visual Studio/C 기초

C언어 malloc()

낙락장송s 2013. 9. 6. 15:37

메모리 영역을 할당하기 위해 라이브러리 함수 malloc()를 사용합니다. 이 함수의 용도는 문자열을 저장하기 위한 메모리 영역을 할당하는 것으로 제한되지 않습니다.

남아 있는 메모리의 양을 확인하기 위해 malloc()함수를 사용해 보겠습니다.

 

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

struct kilo{
 struct kilo *next;
 char dummy[1022];
};                                //1024바이트 단위의 구조체를 정의합니다.

int freemem(void);

main(){
 printf("%dKB의 사용가능한 메모리가 남아있습니다.\n",freemem());
}

int freemem(void)
{
 int cnt=0;
 struct kilo *head, *current, *nextone;

 current=head=(struct kilo*) malloc(sizeof(struct kilo));

 if(head==NULL)
  return 0;       //메모리가 유효하지 않음
 cnt++;

 for(;;)
 {
  current->next=(struct kilo*) malloc(sizeof(struct kilo));
  current=current->next;
  if(current==NULL)
   break;
  cnt++;
 }

 current=head;   //cnt는 할당할 수 있는 kilo형 구조체의 수를 가집니다. 반환하기 전에 모두 해제해야 합니다.

 do
 {
  nextone=current->next;
  free(current);
  current=nextone;
 }while(current!=NULL);

 return cnt;

 

사실 이 방법은 좀 무식한 방법인데요, malloc()함수가 더 이상의 메모리가 유효하지 않다는 것을 나타내며 NULL을 돌려줄 때 까지 계속해서 메모리 블록을 할당하며 반복합니다.