| When writing C, I tend to avoid calling malloc and free directly. * https://github.com/DaveJarvis/mandelbrot/blob/master/memory.... I then apply this same principle of "opening" and "closing" structures throughout the application. Generally, I can quickly verify that the calls are balanced: * https://github.com/DaveJarvis/mandelbrot/blob/master/threads... What's nice about this pattern is that the underlying implementation of exactly how the memory is maintained for a particular data structure (e.g., whether malloc or gdImageCreateTrueColor is called) becomes an implementation detail: * https://github.com/DaveJarvis/mandelbrot/blob/master/image.c The main application opens then closes structures in the reverse order: * https://github.com/DaveJarvis/mandelbrot/blob/master/main.c This means there's only one call to malloc and one call to free throughout the entire application (third-party libraries notwithstanding), allowing them to be swapped out with ease. Aside, logging can follow this same idea by restricting where any text is written to the console to a single location in the code base: * https://github.com/DaveJarvis/mandelbrot/blob/master/logging... |
As a very minor point, calling free(NULL) is well-defined and safe so there is no need for the if-statement in memory_close(). This is very clearly stated in the manual page [1] for instance:
If ptr is a null pointer, no action shall occur.
[1]: https://man7.org/linux/man-pages/man3/free.3p.html