Friday, December 2, 2011

What is the difference between “new” and “malloc” and “calloc”

new/delete

  • Allocate/release memory
    1. Memory allocated from 'Free Store'
    2. Returns a fully typed pointer.
    3. new (standard version) never returns a NULL (will throw on failure)
    4. Are called with Type-ID (compiler calculates the size)
    5. Has a version explicitly to handle arrays.
    6. Reallocating (to get more space) not handled intuitively (because of copy constructor).
    7. If they call malloc/free is implementation defined.
    8. Can add a new memory allocator to deal with low memory (set_new_handler)
    9. operator new/delete can be overridden legally
    10. constructor/destructor used to initialize/destroy the object

malloc/free

  • Allocates/release memory
    1. Memory allocated from 'Heap'
    2. Returns a void*
    3. Returns NULL on failure
    4. Must specify the size required in bytes.
    5. Allocating array requires manual calculation of space.
    6. Reallocating larger chunk of memory simple (No copy constructor to worry about)
    7. They will NOT call new/delete
    8. No way to splice user code into the allocation sequence to help with low memory.
    9. malloc/free can NOT be overridden legally




    Answer

    malloc in a function and new is an operator, and its a good programming practice to use an operator instead of functions, because function itself requires some time to be executed whenever that particular function is called. so the main difference is that we use operators instead of malloc because of the TIME CONSTRAINT.  

    Answer

    1.malloc requires the type casting during decleration , where as new doesn't needed the type casting during decleration 2. when ever we use new for allocating memory along with this it calls the constructor of the class for which object memory is allocated 3. in case of malloc free is the word used to clear the memory, where as delete is the format used in case of new to free the memory after usage 4. malloc is function, where as new is operator..so the time required for execution is less in case of new (it being a operator) as compared to malloc(it being a function)

    http://www.maxi-pedia.com/what+is+heap+and+stack





No comments:

Post a Comment