Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in implementation of malloc and new. Stack implementation?

While allocating memory, the new operator throws an exception if the memory is not available. On the other hand, malloc returns a NULL. What is the reason for the difference in implementation. Also, on static memory allocation, i.e. on the stack, is there an exception if we run out of memory?

I have already gone through the link What is the difference between new/delete and malloc/free? but did not get my answer on the difference in implementation of the two

like image 646
Shrey Avatar asked Jan 20 '23 09:01

Shrey


2 Answers

The problem with C code is that you are supposed to check the return value of function to make sure they worked correctly. But a lot of code was written that did not check the return value and as a result blew up very nicely when you least expected it.

In the worst case scenario it does not even crash immediately but continues on corrupting memory crashing at some point miles down stream of the error.

Thus in C++ exceptions were born.
Now when there is an error the code does not continue (thus no memory corruption) but unwinds the stack (potentially forcing the application to quit). If you can handle the problem you have to explicitly add code to handle the situation before continuing. Thus you can not accidentally forget to not check the error condition; you either check it or the application will quit.

The use of new fits this design.
If you fail to allocate memory then you must explicitly handle the error.
There is no opportunity to forget to check for the NULL pointer. Thus you can't go and mess up memory by accidentally using a NULL pointer.

Also, on static memory allocation, i.e. on the stack, is there an exception if we run out of memory?

Unfortunately you can not rely on this.
It is implementation defined what happens on stack-overflow. On a lot of systems it is not even possible to detect the situation resulting in memory corruption and probably ultimately a crash.

Note

If you #include <new> then there is a no throw version of new that you can use that returns NULL when there is no memory left. It is best avoided unless have some specialized need.

like image 160
Martin York Avatar answered Mar 17 '23 18:03

Martin York


malloc cannot throw an exception, because that would break compatibility with C. new throws an exception because that is the preferred way in C++ to signal errors.

As far as I know, in early versions of C++, new did indeed return 0 on failure,

like image 44
Oswald Avatar answered Mar 17 '23 20:03

Oswald