Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

  1. Can I have both mechanisms malloc/free and new/delete in the same compilation unit (*.o) - of course, respecting the "no-mix" rule ?

  2. 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;
    
like image 941
lalebarde Avatar asked Mar 22 '23 04:03

lalebarde


1 Answers

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.

like image 118
sharptooth Avatar answered Apr 02 '23 11:04

sharptooth