4 ms·
When writing C, I tend to avoid calling malloc and free directly. * https://github.com/DaveJarvis/mandelbrot/blob/master/memory.c https://github.com/DaveJarvis
by thangalin 3y ago
When writing C, I tend to avoid calling malloc and free directly.
* https://github.com/DaveJarvis/mandelbrot/blob/master/memory.c 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.c 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 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 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.c#L30 https://github.com/DaveJarvis/mandelbrot/blob/master/logging...
- unwind 3y agoInteresting. 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 https://man7.org/linux/man-pages/man3/free.3p.html
- thangalin 3y ago> calling free(NULL) is well-defined and safe Probably showing my age. SunOS 4, PalmOS, and 3BSD reputedly crashed. (There were also double free exploits back in 1996.) This further illustrates my point, though: Removing the NULL check is a single conditional to remove, as opposed to littering the free + guard everywhere. In effect, by isolating duplicated pieces of logic, it keeps possibilities open.