Best way to handle memory allocation in C?

后端 未结 12 1749
春和景丽
春和景丽 2021-01-31 11:58

I think I\'ve got a good grasp on how to handle memory in C++ but doing it in C is different I\'m a bit off.

In C++ I\'ve got constructors and destructors, I\'ve got the

12条回答
  •  别那么骄傲
    2021-01-31 12:18

    There's a lot you can do to make your life easier. You already seems to have hit on the idea of creating factories/constructors for your C-objects. That's a good start follow up on it.

    Some other ideas to consider.

    1. don't settle for the standard malloc/free. go looking for a better one that's been opensourced or write one that suites the memory use of the objects that you are creating. also, we're talking C here, you're going to overwrite your objects free more and once and forget to free some, so build some debugging support into your malloc. writing your own is not hard if you cannot find one that meets your needs.

    2. use more than one heap. use one per class of object you create, use temporary heaps if you know you you are going to have a large number of transient objects that are related, this keeps memory fragmentation down and allows you to manage memory according to use.

    3. look at strategies like Objective-C's pools

    4. if you think you understand how C++ works, then adding constructor behavior to memory allocation in an object factory is not so hard to do and using a custom built free can then provide you the capability to call a destructor on the object being free'd giving you back some of the C++ behavior you liked

提交回复
热议问题