Malloc / freeware and new / remote compatibility in C ++?

There is a good comparison of malloc / free and new / delete here , as well as good explanations of how malloc () and free () work. Obviously, we will not mix them - use free with a new one or delete it using malloc.

We see many open source projects with many contributors using both of these mechanisms, subject to the above “no mixing” rule. Usually you have only one way in one file (one author, one preferred option). I developed such a project and I am adding some functions using new / delete. But I come across some curious memory corruptions. Of course, I’m probably responsible for them, but .....

This makes me ask some “naive” questions:

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

  • Can I alternate two mechanisms, as in this code?

    int *a = (int *) malloc (1000 * sizeof int);
    
    int *b = new int[1000];
    
    // some code
    
    free a;
    
    delete[] b;
    
+4
source share
1 answer

Yes, you can alternate them - just use the release function corresponding to the one used for highlighting. The problem only occurs if you use the wrong release function.

, , - , , , , , undefined. . , , .

+6

All Articles