Cleanup code & malloc wrapper

P

Petr Pavlu

Hello,
I have two questions how the functions should be written. I read the FAQ
but didn't find any answer. If there is any please point me out.


I. Cleanup code
Consider I have to open file1, then make some malloc and then open file2.
What is the best solution how to write the cleanup code? See my pseudo-
code ideas.

1. Write appropriate calls before every return
my_function()
{
if (fopen1 failed)
return 1

if (malloc failed) {
fclose1
return 2
}

if (fopen2 failed) {
free
fclose1
return 3
}

...

if (something failed) {
fclose2
free
fclose1
return 4
}

/* everything ok */
fclose2
free
fclose1
return 0
}

2. Use goto statement and an extra variable
my_function()
{
int rv = 0;

if (fopen1 failed) {
rv = 1
goto end
}

if (malloc failed) {
rv = 2
goto end
}

if (fopen2 failed) {
rv = 3
goto end
}

...

if (something failed) {
rv = 4
goto end
}

end:
if (filepointer2 != NULL)
fclose2
if (memorypointer != NULL)
free
if (filepointer1 != NULL)
fclose1
return rv
}

3. Use a similar mechanism as atexit()
my_function()
{
if (fopen1 failed) {
execute_all(stack)
return 1
}
push(stack, fclose, filepointer1)

if (malloc failed) {
execute_all(stack)
return 2
}
push(stack, free, memorypointer)

if (fopen2 failed) {
execute_all(stack)
return 3
}
push(stack, fclose, filepointer2)

...

if (something failed) {
execute_all(stack)
return 4
}

execute_all(stack)
return 0
}

void push(STACK *stack, void (*func)(void *), void *data) ?
Pushing on the stack should be always successful, the stack should have a
static array for functions, there would be assert() to disallow saving
more than an allowed amount of functions...

execute_all(stack) and return X could be defined as
#define RETURN(stack, rv) \
execute_all(stack) \
return rv

4. Define a cleanup macro for every function
my_function()
{
#define RETURN(rv) \
if (filepointer2 != NULL) \
fclose2 \
if (memorypoiter != NULL) \
free \
if (filepointer1 != NULL) \
fclose1 \
return rv

if (fopen1 failed)
RETURN(1)

if (malloc failed)
RETURN(2)

if (fopen2 failed)
RETURN(3)

...

if (something failed)
RETURN(4)

RETURN(0)
#undef RETURN
}

I think the final output will be very large in this case.

5. Another solution
Do you know about some different elegant solution? Smart pointers in C? :)
Or am I doing everything wrongly if my function needs three or more
cleanup functions?


II. My malloc with exit()
Is it good idea using my malloc wrapper like this one?
void *xmalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL) {
fprintf(stderr, "Malloc error.\n");
exit(1);
}
return p;
}
Is it ok to call exit() inside it? Some people says, you should have
free() to every malloc() call (other pair is fopen() and fclose() etc.).
However if a program (and probably also an operation system) doesn't have
enough memory should program give up as soon as possible?


Thanks in advance
 
S

santosh

"]
Hello,
I have two questions how the functions should be written. I read
the FAQ but didn't find any answer. If there is any please point me
out.[/QUOTE]

The FAQ only deals with C questions, not general programming design
issues.
I. Cleanup code
Consider I have to open file1, then make some malloc and then open
file2. What is the best solution how to write the cleanup code? See
my pseudo- code ideas.

1. Write appropriate calls before every return
my_function()
{
if (fopen1 failed)
return 1

if (malloc failed) {
fclose1

Consider that fclose can also fail.
return 2
}

if (fopen2 failed) {
free
fclose1
return 3
}

...

if (something failed) {
fclose2
free
fclose1
return 4
}

/* everything ok */
fclose2
free
fclose1
return 0
}

This is probably okay for simple functions or programs. You might get
rid of the multiple return statements and have a single return
statement return a value that the different control structures set
according to what happens.
2. Use goto statement and an extra variable
my_function()
{
int rv = 0;

if (fopen1 failed) {
rv = 1
goto end
}

if (malloc failed) {
rv = 2
goto end
}

if (fopen2 failed) {
rv = 3
goto end
}

...

if (something failed) {
rv = 4
goto end
}

end:
if (filepointer2 != NULL)
fclose2
if (memorypointer != NULL)
free
if (filepointer1 != NULL)
fclose1
return rv
}

This is an alternate method. Basically it puts of clean-up to a block
of code at the end. This might not work well if the function becomes
large. You'll have to keep the clean-up block and the rest of the
code in careful sync.
3. Use a similar mechanism as atexit()
my_function()
{
if (fopen1 failed) {
execute_all(stack)
return 1
}
push(stack, fclose, filepointer1)

if (malloc failed) {
execute_all(stack)
return 2
}
push(stack, free, memorypointer)

if (fopen2 failed) {
execute_all(stack)
return 3
}
push(stack, fclose, filepointer2)

...

if (something failed) {
execute_all(stack)
return 4
}

execute_all(stack)
return 0
}

void push(STACK *stack, void (*func)(void *), void *data) ?
Pushing on the stack should be always successful, the stack should
have a static array for functions, there would be assert() to
disallow saving more than an allowed amount of functions...

execute_all(stack) and return X could be defined as
#define RETURN(stack, rv) \
execute_all(stack) \
return rv

4. Define a cleanup macro for every function
my_function()
{
#define RETURN(rv) \
if (filepointer2 != NULL) \
fclose2 \
if (memorypoiter != NULL) \
free \
if (filepointer1 != NULL) \
fclose1 \
return rv

if (fopen1 failed)
RETURN(1)

if (malloc failed)
RETURN(2)

if (fopen2 failed)
RETURN(3)

...

if (something failed)
RETURN(4)

RETURN(0)
#undef RETURN
}

I think the final output will be very large in this case.

I think this method introduces a lot of complexity for very little
real gain.

The logic becomes even more complex when you want to try to recover
from resource allocation failures. It then becomes a matter of
deciding what to free, how much to free and what functionality to
recover. You might have to write a program specific resource
acquisition and release infrastructure, to really make all this
functionality easy to understand and flexible.

For small to medium sized programs, one of the above methods will do
fine.
II. My malloc with exit()
Is it good idea using my malloc wrapper like this one?
void *xmalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL) {
fprintf(stderr, "Malloc error.\n");
exit(1);
}
return p;
}

Here a leaf function is taking on the task of deciding whether to
print a diagnostic message and also forcing the program to terminate
with a non-standard return value.

In this scenario you need to register all your clean-up functions
with atexit, so that your program doesn't rely on the OS to recover
resources and close open streams.

It seems to me that it's better to make these kinds of broad policy
decisions higher up in the program's logic than in a relatively
low-level function, like malloc.
Is it ok to call exit() inside it? Some people says, you should
have free() to every malloc() call (other pair is fopen() and
fclose() etc.). However if a program (and probably also an
operation system) doesn't have enough memory should program give up
as soon as possible?

The answers depend on what exactly your program is going to do, and
it's expected runtime, input etc.

Generally, you might consider releasing some non-essential resources
and trying again. If that's not possible, or does not work, you
should still try a normal exit, instead of calling abort.
 
B

Ben Bacarisse

Petr Pavlu said:
Hello,
I have two questions how the functions should be written. I read the FAQ
but didn't find any answer. If there is any please point me out.


I. Cleanup code
Consider I have to open file1, then make some malloc and then open file2.
What is the best solution how to write the cleanup code? See my pseudo-
code ideas.

Answering general questions like this is problematic. The right way
in some designs is wrong in others. For example, it is somtmes more
helpful to try all the file opens (even after one has failed) since
the extra message might help the user. In other cases, backing out as
soon a possible is the best option.

One thing that helps a lot it to be in control of what is in your
pointers. You can then safely clean up in one go. For example I might
write:

int *p = NULL;
FILE *f1 = NULL, *f2 = NULL;
if ((f1 = fopen(...)) &&
(f2 = fopen(...)) &&
(p = malloc(...))) &&
/* do the work */
}
free(p); /* safe even in p == NULL */
if (f1) fclose(f1);
if (f2) fclose(f2);

Some people would not initialize f1 (since it is immediately assigned
to) but this way you won't forget if you re-order your 'if' condition.

Of course, if you want to provide more error messages you need to do
more, but error reporting was not part of your suggested outlines.

II. My malloc with exit()
Is it good idea using my malloc wrapper like this one?
void *xmalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL) {
fprintf(stderr, "Malloc error.\n");
exit(1);
}
return p;
}
Is it ok to call exit() inside it?

In my opinion this is fine provided:
(1) you pass EXIT_FAILURE to exit rather than 1;
(2) you use this only because that is what you would have written
anyway (in other words, you are just tidying up your code)
(3) you don't encourage widespread use of this function. Its
simplicity is beguiling, but its behaviour is antisocial in many
situations.
 
C

Chris Torek

II. My malloc with exit()
Is it good idea using my malloc wrapper like this one?
void *xmalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL) {
fprintf(stderr, "Malloc error.\n");
exit(1);
}
return p;
}
[/QUOTE]

[Elsethread, someone notes that exit(1) should probably be
exit(EXIT_FAILURE) or similar.]

It seems to me that it's better to make these kinds of broad policy
decisions higher up in the program's logic than in a relatively
low-level function, like malloc.

Indeed.

The seductivity of xmalloc(), as I will call this "malloc and exit
on failure", is that in small programs, the "higher up" decision
as to what to do on failure turns out to be "print a message and
exit". The danger is that small programs grow -- and soon that
decision turns out to be wrong. By then, however, the concept of
"sometimes one can continue after a failing malloc" may be lost
upon the maintenance programmer.

I might suggest, then, that xmalloc() generally be rewritten as:

void *xmalloc(size_t size, int exit_on_failure) {
void *p;

p = malloc(size);
if (p == NULL && exit_on_failure) {
#if HAVE_ZU_FORMAT /* e.g., C99 */
fprintf(stderr, "malloc: failed to allocate %zu bytes\n", size);
#else
fprintf(stderr, "malloc: failed to allocate %lu bytes\n",
(unsigned long)size);
#endif
exit(EXIT_FAILURE); /* or exit(exit_on_failure), perhaps */
}
return p;
}

Perhaps it would be even better to have a "flags" argument, with
one flag for "produce a message to stderr on failure" and one for
"exit on failure". Either way, it becomes clear that:

result = xmalloc(size, EXIT_FAILURE);

can later be replaced with:

result = xmalloc(size, 0);
/* and test "result" */

and therefore -- this is the crucial step, without which the above
is a bit silly since one can simply change xmalloc(n) to malloc(n)
-- any *intermediate* level function, like this one:

struct foo *foo_frobnicate(struct bar *p, int flags) {
struct foo *result;

result = xmalloc(sizeof *result, flags);
if (result == NULL)
return NULL;
... do some work ...
result->field = whatever(p);
... do more work ...
return result;
}

*must* still test for a NULL from xmalloc().

In other words, the point of making xmalloc() only *optionally*
exit is to make it clear, during development, that xmalloc() does
not *unconditionally* exit, and therefore only those callers who
pass it the "yes, please exit on failure" flag are allowed to ignore
the possibility of failure.
 
G

gw7rib

[Apologies if this appears more than once. I don't think Google
actually submitted it last night, though it spent half an hour
attempting to do so.]

I. Cleanup code
Consider I have to open file1, then make some malloc and then open file2.
What is the best solution how to write the cleanup code? See my pseudo-
code ideas.

1. Write appropriate calls before every return
my_function()
{
if (fopen1 failed)
return 1

if (malloc failed) {
fclose1
return 2
}

if (fopen2 failed) {
free
fclose1
return 3
}

...

if (something failed) {
fclose2
free
fclose1
return 4
}

/* everything ok */
fclose2
free
fclose1
return 0

}

Wouldn't it be possible to do this by careful use of nested ifs? For
example:


my_function()
{
int error = 0;
fopen1
if (fopen1 worked) {
malloc
if (malloc worked) {
fopen2
if (fopen2 worked) {
more stuff here
fclose2
} else error = 3
free
} else error = 2;
fclose1
} else error = 1;
return error;
}

Hope that is useful.
Paul.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top