Alex Rivera | Logout

Taming the malloc/free beast -- tips & tricks

Asked 2010-05-12T08:04:29.497
11

I've been using C on some projects for a master's degree but have never built production software with it. (.NET & Javascript are my bread and butter.) Obviously, the need to free() memory that you malloc() is critical in C. This is fine, well and good if you can do both in one routine. But as programs grow, and structs deepen, keeping track of what's been malloc'd where and what's appropriate to free gets harder and harder.

I've looked around on the interwebs and only found a few generic recommendations for this. What I suspect is that some of you long-time C coders have come up with your own patterns and practices to simplify this process and keep the evil in front of you.

So: how do you recommend structuring your C programs to keep dynamic allocations from becoming memory leaks?

Edit
Report

1 Answer

4

It won't be foolproof (but that's probably to be expected with C), and it might be hard to do with lots of existing code, but it helps if you clearly document your code and always state exactly who owns allocated memory and who's responsible for freeing it (and with what allocator/deallocator). Also, don't be afraid to use goto to enforce a single-entry/single-exit idiom for non-trivial, resource-allocating functions.

answered 2010-05-12T09:35:56.750

Your Answer