Best way to handle memory allocation in C?

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

    The usual way is

    MyType *ptr = malloc(array_size * sizeof *ptr);
    

    But if you want to be compatible with c++, do

    MyType *ptr = (MyType*) malloc(array_size * sizeof *ptr);
    

    You can also make a macro

    #define MALLOC( NUMBER, TYPE ) ( TYPE * ) malloc( NUMBER * sizeof( TYPE ) )
    MyType *ptr = MALLOC(10, MyType);
    

    Of course, with no RAII, make sure sometime later you have

    free(ptr);
    

提交回复
热议问题