I’m converting a type from a C-style struct to a C++-style struct; I’m adding a member which will force the type to need a constructor, and I must therefore switch from malloc and free to new and delete. I can find everywhere the type is allocated (due to the conventions of this codebase) by looking for sizeof(TYPE).
Is there any way I can locate all the instances where pointers of that type are passed to free? I realise that, since the argument to free is void* that’s not a guarantee I’ve found everywhere the type is freed.
For instance, can I overload free somehow so that I’ll get a compilation error wherever free(TYPE*) is called, but not anywhere else?
You can certainly give it a go. For example:
Thanks to ADL, that call to
freeis tomy::free, so the code fails to compile. Obviously this wouldn’t catchfree((void*)ptr);, since calls tofreewith arguments other thanmy::TYPE*are unaffected.As I’ve written it, there need to not be any calls to
freeinside namespacemy, or in code that hasusing namespace my;. So you might want to use a newly-invented namespace for the purpose. Or write a less catch-all template, I improvised that one.It also doesn’t catch fully-qualified calls to
std::free. It’s undefined behavior to overloadstd::free(or anything in namespace std), but if necessary you’d probably get away with it just for the purpose of finding call sites. Something like this: