Best way to handle memory allocation in C?

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

    The sad truth is that C isn't really designed to encapsulate all those memory management issues.

    If you look at fairly high quality APIs like POSIX, you'll see that the common pattern is that you pass a pointer to a pointer to a function, which then allocates the memory, and that you later pass it again to a function that destroys it.

    It's not necessarily elegant, but I don't think there are many ways to make it really elegant without simulating OOP in C.

提交回复
热议问题