Best way to handle memory allocation in C?

后端 未结 12 1754
春和景丽
春和景丽 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:25

    One way I "hide" the memory allocation and de-allocation is to pass it off to custom containers. Pass the container an un-malloced object. Let it worry about malloc and when I remove the object let it worry about the free. Of course this only works if you are only storing an object in one container. If I have object references all over the place I will create the equivalent of constructor and destructor methods with c syntax:

     glob* newGlob(); 
     void freeGlob(glob* g);
    

    (by object I mean anything you would point to - not c++ objects).

提交回复
热议问题