Synopsys R&D Bloomberg LP Interview Question
Financial Software DevelopersI got the same question on my interview. First answer is that malloc is allocation method from C and new is allocation method from C++. There is no object-oriented programming in C, and therefore malloc don't know about constructors. So the basic answer is that new allocates memory and calls the constructor, where malloc only allocates memory and return pointer on the void* without any values initalized (we have to memset them to 0). I also mentioned that malloc and new use different allocation techniques so we shouldn't use malloc with delete and new with free.
@Kozikowski: You are correct. One more difference is there.
malloc always returns 0 (or NULL) when it runs out of memory. but new used to do this until Microsoft Visual Studio 6.0 but after C++03 standard (came in 2003, latest so far, C++0x is about to come!) and in later compiler's new NEVER EVER returns 0 or NULL, it always throws std::bad_alloc exception if it runs out of memory, however you can still change this behavior to old (returning 0) behavior by using this syntax!
int *p = new(nothrow) int;
@bobby.teja: Where did you find that? It's absolutely wrong! Are you just making guesses here?
Neither new Nor malloc releases memory after program termination. There are 2 cases to this scenario:
1. If you new/malloc some memory and never delete/free that memory then during the program execution this is called memory leak and can lead to undefined behavior of the program causing crashes, overwriting memory, etc.
2. Bobby, if you are talking about program termination then don't blame new/malloc for releasing memory, it is the runtime system that unloads the process from main memory (RAM) and thus there is no question of releasing memory or memory leak, because the program is not in main memory so whole memory acquired by the program has been unloaded from the main memory.
if memory cant b allocated...malloc returns NULL
if memory cant b allocated...new throws exception
Two more :
1. new can be overloaded, malloc doesn't know what overloading is :)
2. new doesn't require you to specify size of mem to be allocated, malloc cannot work without it.
malloc returns void pointer
- yours.ramesh February 10, 2011new returns the pointer to the object that is created (eg: A *a = new A(); returns pointer of type A)
malloc does not call constructor
new calls constructor