Best way to handle memory allocation in C?

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

    You may think that what I say is strange, but there is no big difference between C++ and C. C has RAII as well. RAII does not belong to C++ only.

    Only thing you should have enough discipline to do management.

    C++ class:

    class foo {
    public:
       ofstream ff;
       int x,y;
       foo(int _x) : x(_x),y(_x){ ff.open("log.txt"); }
       void bar() { ff< f(new foo);
       f->bar();
    }
    

    C object

    typedef struct FOO {
        FILE *ff;
        int x,y;
    } *foo_t;
    
    foo_t foo_init(int x)
    {
       foo_t p=NULL;
       p=malloc(sizeof(struct FOO)); // RAII
       if(!p) goto error_exit;
       p->x=x; p->y=x;
       p->ff=fopen("log.txt","w");   // RAII
       if(!p->ff) goto error_exit;
       return p;
    error_exit:   // ON THROW
       if(p) free(p);
       return NULL;
    }
    
    void foo_close(foo_t p)
    {
       if(p) fclose(p->ff);
       free(p);
    }
    
    void foo_bar(foo_t p)
    {
       fprintf(p->ff,"%d\n",p->x+p->y);
    }
    
    int main()
    {
      foo_t f=foo_init(1);
      if(!f) return 1;
      foo_bar(f);
      foo_close(f);
      return 0;
    }
    

提交回复
热议问题