페이지

Include Lists

2017년 1월 12일 목요일

Malloc/Free 과 New/Delete 의 차이




 What
   - new/malloc의 사용법 및 장단점 파악

 Why
   - 상황에 따른 올바르게 사용법 학습
   - 사소하지만 기본적인 개념학습

 Usage
   - Searching New/Malloc

Malloc/Free 과 New/Delete 에 대한 궁금증이 생겼다..


과연 두 기능의 차이는 무엇일까..










기본적으로 Malloc/Free는 C Style 의 공간 할당 방법이다.
그렇기 때문에, 위 그림에서 처럼 override 나 생성자 소멸자를 호출 할 수 없다.
오롯이 공간만 할당을 한다.

New/Delete의 경우 C++ style의 공간 할당 방법이다.
특징은 생성자와 소멸자, override 등의 기능을 사용할 수 있다는 것이다.

또하나 차이점은, 
malloc 은 공간의 재할당을 할 수 있고(realloc),  new는 불변이라는 차이점이 있다.


예제를 통해 확인해 보았다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
struct Memery
{
    explicit Memery()
    {
       std::cout << "----- Memery constructor()" << std::endl;
    };
    ~Memery(){
       std::cout << "----- Memery deconstructor()" << std::endl;
    };
};
 
class MemoryPool
{
public:
    explicit MemoryPool(){};
    ~MemoryPool(){};
 
    std::array<Memery, 1> m_pool;
};
 
int main()
{
    std::cout << "malloc" << std::endl;
    Memery* mem = nullptr;
    mem = (Memery*)malloc(1*sizeof(Memery));
 
    std::cout << "free" << std::endl;
    free(mem);
 
    std::cout << "new constructor" << std::endl;
    MemoryPool* pool = new MemoryPool;
 
    std::cout << "delete deconstructor" << std::endl;
    delete pool;
    pool = nullptr;
}
cs
위 예제처럼,
메모리라는 struct의 생성자와 소멸자에 각각 message를 호출하도록 하였다.


결과 화면


이렇게 되니, 같은 크기의 객체를 할당하더라도 속도차이는 발생할 수 있다.

위 객체를 100000000 만큼 생성 했을 경우이다. 




 (msec)




위 코드에서 간과 한것 중 하나는 raw ptr과 std::array 객체의 차이도 존재 할 수 있을 것이라 생각은 해보았는데, 테스트 결과

속도차이는 존재 하지 않았다. 어쨌든 std::arrary 를 한번은 호출하는건 사실 이나,

그런걸 감안하고서라도 10배 정도 차이가 난다는건 기본 생성자/소멸자를 호출 하기 때문인것이지.. 오롯이 그런 이유인건지??



출처: <http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free>