When to use Malloc instead of New

Duplicate of: In what cases do I use malloc vs new?

Just re-reading this question:
What is the difference between "new" and "malloc" and "calloc" in C++?

I checked the answers but nobody answered the question:

  • When would I use malloc instead of new?
  • There are a couple of reasons (I can think of two).
    Let the best float to the top.


    A couple that spring to mind:

  • When you need code to be portable between C++ and C.
  • When you are allocating memory in a library that may be called from C, and the C code has to free the allocation.

  • From the Stroustrup FAQ on new/malloc I posted on that thread:

    Whenever you use malloc() you must consider initialization and convertion of the return pointer to a proper type. You will also have to consider if you got the number of bytes right for your use. There is no performance difference between malloc() and new when you take initialization into account.

    This should answer your question.


    In C++, just about never. new is usually a wrapper around malloc that calls constructors (if applicable.)

    However, at least with Visual C++ 2005 or better, using malloc can actually result in security vulnerabilities over new.

    Consider this code:

    MyStruct* p = new MyStruct[count];
    MyStruct* p = (MyStruct*)malloc(count* sizeof(MyStruct));
    

    They look equivelent. However, the codegen for the first actually checks for an integer overflow in count * sizeof(MyStruct). If count comes from an unstrusted source, it can cause an integer overflow resulting in a small amount of memory being allocated, but then when you use count you overrun the buffer.

    链接地址: http://www.djcxy.com/p/13768.html

    上一篇: 用C ++中的删除和自由功能混淆

    下一篇: 何时使用Malloc而不是New