Memory management

This is a discussion on Memory management within the C Programming forums, part of the General Programming Boards category; What's the easiest (well not easiest), but best method for memory management if i'm allocating memory for structs, strings, arrays, ...

Memory management

What's the easiest (well not easiest), but best method for memory management if i'm allocating memory for structs, strings, arrays, etc.. Is there some way I could just store all the pointers in a linked list and cycle through it free'ing all the memory?

I actually have it set up in that way, but it is only set up for a single struct, i.e. the linked list only keeps track of the memory allocated for a struct, than free's everything automatically. Just wondering if there was a generic way to do it so i could manage all memory in an application. Is there a garbage collecting library, or something out there already that people use?

I guess it's kind of like in an OO language like java, using <generic> or "Object" to overshadow anything you might use, than using casting if you want to manipulate something. Just an easy way to group everything together.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

I actually have it set up in that way, but it is only set up for a single struct, i.e. the linked list only keeps track of the memory allocated for a struct, than free's everything automatically. Just wondering if there was a generic way to do it so i could manage all memory in an application. Is there a garbage collecting library, or something out there already that people use?

Sure -- you could just have your linked list node structure contain a void pointer. A void pointer can point to any type, and yet you can still free() it, so it works out. Other information you might want to store might include a reference count (if you're going to all this trouble you might as well), and perhaps the size of the block, along with other information like the file and line where the block was allocated (__FILE__ and __LINE__). Having all this extra information can often help you debug your program, if you feel like implementing it.

That said, of course there are other reference counters and garbage collectors available on the internet -- but using them isn't as much fun as writing your own. That's what I did in xuni, but I wouldn't recommend looking at that particular part of xuni's code. :P

"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell