프로그래밍/C++2013. 5. 18. 19:42
int *p1;
struct employee{
  char name[20];
  int age;
  float sal;
} *p2;

p1 = new int;  //allocates 4 bytes
p2 = new employee; //allocates 32? bytes

int *p3;
p3 = new int[30];  //allocates memory for storing 30 inters

delete p1;
delete p2;
delete [] p3;

에 비해, malloc/free를 쓴다면....

p1 = (int*) malloc (sizeof(int));
p2 = (struct employee*) malloc (sizeof(struct employee));
p3 = (int*) malloc (sizeof(int) * 30);

malloc은 void 타입을 리턴하기 때문에, typecasting도 해 줘야 하고,  new의 경우, array dimension을 지원한다.  물론 variable dimension(dynamic size)도 지원한다.
훨씬 낫지 않은가?

그렇다면 new / free, malloc / delete 이런 조합도 가능할가? 안된다.

한가지 더...
new/delete는 오브젝트들을 생성/파괴 할 수 있는 반면, malloc/free는 메모리를 할당/해제 한다.  이는 중요한 부분으로 클래스 생성/파괴에서 new/delete을 쓰는 이유이다.
Posted by code cat