C/C++ Basic– the differs between [malloc&free] and [new &delete]

來源:互聯網
上載者:User

1.basic concepts
    malloc&free  and new&delete are all used to request memory allocation and release memory allocated from heap area.
    eg.
    malloc.h must be referenced when using malloc&free
   i)
    int *array;
    array=(int *)malloc(4*sizeof(int));// declare an array which has four int elements
     ....
    free(array);//release the memory which is allocated to array.
  ii)
    int *array
    array=new int[4];
    ...
    delete[] array;
all these two cases works the same. but what is their differs then? are they the same functioanlity? NO!

2.diffs.
    we can only say that in some cases, they work the same.that is to say, we can use malloc&free to take place of new&delete. but this can not applied all the time.
    the main reason is :malloc will not invoke class construtor in C++, while new do. At the same time, free will not invoke destructor,while delete do.
    eg.
    class TDate
{
    public:
       TDate()
        {
        month=1;
        day=1;
        year=1;
        printf("constructor is invoked");
        }
        ~TDate()
        {
        printf("destructor is invoked");
        }
    protected:
        int month;
        int day;
        int year;
}

case 1: use Malloc
        TDate *p;
        p=(TDate *)malloc(sizeof(TDate));//do not invoke constructor at all
        ...
        free(p);//do not invoke destructor at all
    in this case, the constructor of TDate will not be invoked. so all its memebers can not be initialized.

case 2: use new
        TDate *p;
        p=new Tdate;//invoke constructor to initialize the instance
        ...
        delete p;//invoke destructor to release resource.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.