malloc/free and new/delete compatibility in C++?
There is a nice comparison of malloc/free and new/delete here, and good explanations how malloc() and free() work here. Obviously, we shall not mix them - use free with new or delete with malloc.
We can see a lot of open source projects, with many contributors, using both of these mechanisms, while respecting the above "no-mix" rule. Usualy, you have only one way in one file (one author, one preference). I have forked such a project and I am adding some functionalities with use of new/delete. But I encounter some curious memory corruptions. Of course, I am probably responsible of them, but.....
That leads me to ask some "naive" questions :
Can I have both mechanisms malloc/free and new/delete in the same compilation unit (*.o) - of course, respecting the "no-mix" rule ?
Can I interleave the two mechanisms, like in this code ?
int *a = (int *) malloc (1000 * sizeof int);
int *b = new int[1000];
// some code
free a;
delete[] b;
Yes, you can interleave them - just use a deallocation function matching the one used for allocation. The problem only arises if you use a wrong deallocation function.
Note that it's not that easy when you have several libraries - those might use different heaps and so even though you use a right named function it might happen to be implemented in the wrong module and so use the wrong heap which will drive you right into undefined behavior. See this answer for a better idea of what I'm talking about here.
链接地址: http://www.djcxy.com/p/78538.html