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
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;
}