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

This feels slightly untrustworthy. What if there are still external references to subfields of a struct? I think it's probably safer to just write explicit constructors (that allocate and initialize) and destructors (to free properly) for the things you use.


I have used talloc for a medium-sized project, and it was quite refreshing. Of course, it all depends on your program's structure. An hierarchical allocator naturally fits hierarchical data structures and containers, so parsers for example can benefit immensely in my experience.

You are correct in that you can just write constructors and destructors, but then you still need to worry about error handling, double-frees and whatnot. With an allocator like talloc, you just state the relationships during the allocation, and afterwards only worry about the high-level structure.

One thing which can be somewhat cumbersome is the need to pass around those "contexts"; for example, if you allocate an array of some struct, and you need to allocate additional memory inside that struct, your context will presumably be the array, and so you need to have access to it. One solution I have found which is helpful in most, but not all, situations is to use the wonderful container_of[1] macro, which enables you to do upcasting using some pointer trickery. And of course, it does cost some performance as they say on their homepage.

[1] http://www.kroah.com/log/linux/container_of.html


I invariably find myself doing this in C projects because not doing it is a serious violation of DRY--writing possibly hundreds of lines of free (foo->bar); free (foo->baz); free (foo->quux->fnord); ... ; free (foo) is not only hugely error prone, but a waste of everyone's time.


Why does everyone conflate allocation and initialization?


RAII, at a guess.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

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

Search: