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
Part of the confusion is that it is inherently more difficult in C. malloc
and free
are similar to new
and delete
: malloc
allocates new memory, and returns a pointer to that memory. free
makes that memory available again, so long as it's memory that was allocated using malloc. Otherwise, it just makes hash of some chunk of memory. It doesn't care.
The important thing with malloc/free is to decide on and consistently maintain a disciplined use. Here are some hints:
ALWAYS check the returned pointer from malloc for NULL
if((p = (char *) malloc(BUFSIZ)) == NULL {
/* then malloc failed do some error processing. */
}
For belt and suspenders safety, set a pointer to NULL after freeing it.
free(p);
p = NULL ;
try to malloc and free a chunk of memory within the same scope if possible:
{ char * p ;
if((p = malloc(BUFSIZ)) == NULL {
/* then malloc failed do some error processing. */
}
/* do your work. */
/* now you're done, free the memory */
free(p);
p = NULL ; /* belt-and suspenders */
}
When you can't, make it clear that what you're returning is malloc
'ed memory, so the caller can free it.
/* foo: do something good, returning ptr to malloc memory */
char * foo(int bar) {
return (char *) malloc(bar);
}