I'm working on a library that has at least one function that returns dynamically allocated memory.
Since this library will most likely be abused by a bunch of people that have no idea what they are doing, I'm concerned about users ending up allocating lots of memory through the library and never free()ing it. Because of that, I'd like to try to somehow keep track of all memory that is returned this way, and make sure that it is cleaned up, at the very least, upon program exit.
The first option is to not do anything about cleaning up the memory and say, "That's the programmer's problem." I'm willing to go with this approach if that needs to be done, but I still like the idea of being smart about memory and making sure that, as a matter of principle, it is cleaned up before termination. Also, the library will most likely be geared towards newer programmers, so even though free()ing memory is a rather simple task, I don't want to bank on them doing it.
Another option that I see is to register a function using atexit() that will go through all memory allocated in this manner and free() it upon program termination, thus guarenteeing that memory is free()ed. I could supply an xfree() function for the user to use that would, in addition to calling free(), would also remove that pointer from the table. This seems to overcomplicate things. If I'm worried about a programmer using free(), I doubt they would deal with a non-standard function. A second problem with this is if the user decides to deallocate the memory directly using free(), because this will result in a double free, as well as a needless behind-the-scenes memory tracking system.
So naturally complicating this beyond necessity, here are my questions:
- Given that my library will most likely be used by relatively newer programmers, should it keep track of memory allocated that is returned to said programmers?
- If memory tracking should be done, what is the best way of keeping track of memory?
- If memory cleanup should be done by the library, what should be the best method ensure that double free()ing is not performed?