Subject: Re: release time?

Re: release time?

From: Peter Stuge <peter_at_stuge.se>
Date: Thu, 21 Jan 2010 22:36:22 +0100

Alexander Lamaison wrote:
> > A function brings a new scope which may not always work.
..

> > Cleaning up ptr in the above example is the point. Instead of
> > duplicating cleanup code in every single error handling branch within
> > main stuff, all cleanup code is in one single location.
>
> This should still be done with a function. Arguably, that's what
> they were invented for.

I will argue that to no end. What is this about though? goto? The
point Ken or whoever it was wanted to make is that goto should not be
used to jump between scopes. What people seem to have interpreted
that into is that gotos should never be used. I have so far not seen
a big advantage of backwards gotos in C, so my simplest rule becomes
that forward gotos are usually if not always OK.

> static int cleanup(char * ptr, int ret)
> {
> if(ptr)
> free(ptr);
> return ret;
> }
>
> main() {
> int ret=1;
> char *ptr=NULL;
> ..
> if(some_error)
> return cleanup(ptr, ret);
> ptr=malloc(1024*1024);
> if(NULL==ptr) {
> perror("malloc");
> return cleanup(ptr, ret);
> }
>
> /* main stuff */
> return cleanup(ptr, 0)
> }
>
> This makes very clear what is being cleaned up when and where.

Wow, eh, ok.. I don't like this, to say the least. It might look neat
now that it only needs to consider one single variable for cleanup,
but it already duplicates two things (return and ret) without gain.
And what will this look like when there's not just one variable to
clean up but say four or five? (probably not so uncommon)
Not to mention that it makes for an assymmetric code flow, where ptr
is allocated in one function, but freed in another. This needs more
resources when keeping the program in one's head.

//Peter
_______________________________________________
libssh2-devel http://cool.haxx.se/cgi-bin/mailman/listinfo/libssh2-devel
Received on 2010-01-21