An early problem with link counting is that it’s relatively easy to count the original link by putting the code in the malloc / free custom implementation, but it’s pretty difficult to determine if the first recipient passes this address to other users.
Since C does not have the ability to override the assignment operator (to count a new link), basically you have a limited number of options. The only one that can override the assignment is macrodef, since it has the ability to rewrite the assignment into something, which leads to an increase in the reference count.
So, you need to “expand” a macro that looks like
a = b;
in
if (b is a pointer) { // this might be optional, if lookupReference does this work struct ref_record* ref_r = lookupReference(b); if (ref_r) { ref_r->count++; } else { // error } } a = b;
The real trick would be to write a macro that can identify the purpose and paste the code without introducing other unwanted side effects. Since macrodef is not a complete language, you may run into problems when a match becomes impossible.
(jokes on how to see nails, where you learn how to use a hammer, have an interesting parallel here, except when you have only a hammer, you better learn how to make a nail).
Other parameters (perhaps more reasonable, perhaps not) are to keep track of all the address values assigned by malloc, and then scan the program stack and heap for address matching. If you match, you could find a valid pointer, or you could find a string encoded with luck; however, if you do not agree, you can certainly release the address; provided that they do not store the address + offset calculated from the source address. (perhaps you can macrodef detect such offsets and add an offset as multiple addresses when scanning for the same block)
In the end, there will be no reliable solution without creating a help system where you pass back links (pretending addresses); hiding real addresses. The downside of this solution is that you have to use the library interface every time you want to deal with an address. This includes the “next” element in the array, etc. Not very C-like, but a pretty good approximation of what Java does with its links.