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, ie 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
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, ie 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.
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,
One important difference, I suppose, lies in the fact that :
malloc
is the C-way of allocating memories ; and there were no exceptions in C new
is the C++, object-oriented and all, way ; and there are exceptions in C++, and using them is more clean.
Why keep malloc
in C++ ? I suppose it's because C++ compiler can also work with C code...
... But I've often heard (from teachers, while I was still at school, a couple of years ago) that using malloc
in C++ is discouraged, and new
should be used instead.
上一篇: 部分类模板专业化是这个设计问题的答案吗?