Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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...



Interesting.

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


> 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: