Reputation: 2409
I am dealing with some legacy C/C++ code where memory is allocated using malloc
as well as using new
. I want to create a generalized wrapper function to deallocate the memory using either free
or delete []
, depending on how it is allocated.
Is there a way to determine how memory is allocated ? Here is a pseudo code.
double *x;
double *y;
x = (double *) malloc(size);
y = new double [size]
doSomething();
deallocateMemory(x, y);
I want deallocateMemory
to determine whether to call free
or delete []
. Any help would be appreciated.
Upvotes: 3
Views: 2203
Reputation: 70243
You can implement malloc()
yourself instead of using the implementation provided by the standard library. You can also overload the operators new
and delete
. Nothing keeps you from adding your own bookkeeping to either of these implementations, so yes, this is perfectly possible.
Is it recommended? No it isn't.
This smacks of an attempt at implementing garbage collection. If this is true, you are looking at C++ from the wrong way. C++ does have its cleanup facility, which is its destructors. There are ready-made implementations of pointer containers, which in their destructors clean up the allocated memory. Others have mentioned them, and I don't copy-paste from other people's answers.
Upvotes: 6
Reputation: 56479
You want to write
a generalized wrapper function to deallocate the memory
then you need to write
a generalized wrapper function to allocate the memory
and, it is not recommended at all. Try to make your goal clean. If you have to deal with malloc/free
pointer in some part of your code and you can not modify malloc
parts, then try not to mix that part with your new/delete
part.
Otherwise, you have no standard way to determine what allocation method is used for a pointer.
Upvotes: 2
Reputation: 145204
Wrap the raw pointers in appropriate smart pointers (e.g. std::unique_ptr
, std::shared_ptr
) as soon as you take ownership.
Also, order a nine-tail cat and flog the persons responsible for the mess.
Upvotes: 6