본문 바로가기

C언어/강의

2010년 12월 03일 금요일 malloc() 함수 (정리중)

malloc()함수
malloc()함수는 heap영역에 메모리를 할당한다. 메모리의 부족으로 할당에 실패하면 NULL을 반환. 
프로그램의 실행이 끝나기 전에 반드시 free()함수를 호출하여 할당을 해제해 주어야한다. 만약 해제하지 않으면
메모리에 그대로 남아있어 계속 쌓이다 보면 결국 메모리의 용량이 부족하게 되는 현상이 나타난다. 
#include <stdio.h>
#include <stdlib.h>    // malloc() 함수 사용 
#include <string.h>    // strcpy() 함수 사용 

typedef struct tag_student
{
  char name[20];
  int score;
} student;

int main()
{
  student st[3];
  student *sp;
  int i;

  sp=(student*)malloc(sizeof(student));
  if(sp==NULL)  
  {  // 메모리 할당 실패할 경우 
    printf("allocation error\n");
    exit(-1);  // 프로그램을 종료 (return(main함수를 종료)을 추천)
  }
  
  i=0;  // 초기화는 반복문 앞에 써주는 것이 좋다.
  while(i<3)
  {
    printf("Please enter student name & score : ");
    scanf("%s %d", sp->name, &sp->score);
    //strcpy(st[i].name, sp->name);  // 배열에 복사 
    //st[i++].score=sp->score;
    st[i++]=*sp;  // 위와 같다.
  }
  free(sp);

  for(i=0; i<3; i++)
  {
    printf("student name : %s,\tscore : %d\n", st[i].name, st[i].score);
  }
  return 0;
}