No. Use free
to free memory allocated with malloc
, delete
for single objects allocations with new
and delete []
when using new
on arrays.
Mixing and matching may appear to work (it's undefined behaviour, and "undefined" included "works fine" and "sort of works fine most of the time, but crashes on thursdays in months starting with M on days that are divisible with 3 or 7 and the operator has shirt with stripes") - and may indeed work on SOME types of systems, but fail on others, depending on exactly how malloc
and new
and their respective free
and delete
functions are implemented.
It is fine to call a function that returns a pointer to some memory that is later freed with the appropriate call. It is "nicer" if you actually implement a pair of functions, where one allocates and the other destroys the data. This is particularly important if the data-structure allocated isn't trivial (e.g. you have allocations inside the outer allocation).
Also consider what happens if you decide that "Oh, I'd like to use new int[size];
instead of malloc(size * sizeof(int));
in the mallocTest()
". Now every place that calls mallocTest()
will have to change so that it calls delete []
instead of free
that you corrected it to after reading this answer.
[Just spotted that your code is broken, and probably won't compile, certainly won't allocate space: (int *)malloc[size];
doesn't do what you want it to do, and I'm pretty sure is illegal, as indexing a function is invalid]
And finally, the "best" solution is wrap all allocations in an object, such that the destructor of that object destroys the data allocated within the object. So, for example, use std::vector<int>
instead of allocating with malloc
.