If my function return a pointer on a memory area, where do I free it? [snip]
But force anybody to calling free() after use foo() not elegant solution,
for my mind... How can I avoid posible memory leaks if somebody forget
to call free()?
You can design a callback interface to someone that wants the
memory:
[snip code example]
ITYM void bar(void) here.
Wow -- I'd never seen that approach before! It's... interesting,
but I can't really see myself ever using it.
[Just in case the OP didn't get it the first time around: here,
'bar' is the "main" function of the program, and 'foo' is the
function that encapsulates everything to do with a single dynamic
object. 'mycallback'/'cb' is a pointer to a function that says,
"After creating the object, do this and this and this; once that's
done, it's safe to free the object again."]
So to use my favorite example, we could take an image format
converter that looked like this [NOT REAL CODE]:
struct Im
{
unsigned char *data;
int w, h;
};
int main(int argc, char **argv)
{
struct Im *image;
ReadPGM(argv[1], &image);
WritePPM(argv[2], image);
free(image->data);
free(image);
return 0;
}
void ReadPGM(const char *fname, struct Im *im)
{
/* something like... */
im = malloc(sizeof *im);
im->w = im->h = 42;
im->data = malloc(im->w * im->h);
}
and transform it into this:
static const char *OutFileName = NULL;
int main(int argc, char **argv)
{
OutFileName = argv[2];
ProcessPGM(argv[1], write_it_out);
return 0;
}
void write_it_out(struct Im *im)
{
WritePPM(OutFileName, im);
}
void ProcessPGM(const char *fname, void (*cb)(struct Im *))
{
struct Im *image;
ReadPGM(argv[1], &image);
cb(image);
free(image->data);
free(image);
}
Uglier in this case, but possibly this could save a few
keystrokes and possible memory leaks down the road.
HTH,
-Arthur