By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,978 Members | 1,831 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,978 IT Pros & Developers. It's quick & easy.

Cleanup code & malloc wrapper

P: n/a
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
Jul 18 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On Wednesday 18 Jul 2007 1:59 pm, in comp.lang.c, Petr Pavlu
<se*********@dagobah.czwrote:
Message ID: <f7**********@ns.felk.cvut.cz>
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.
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.
Jul 18 '07 #2

P: n/a
>On Wednesday 18 Jul 2007 1:59 pm, in comp.lang.c, Petr Pavlu
><se*********@dagobah.czwrote:
>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;
}
[Elsethread, someone notes that exit(1) should probably be
exit(EXIT_FAILURE) or similar.]

In article <f7**********@aioe.orgsantosh <sa*********@gmail.comwrote:
>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.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (4039.22'N, 11150.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jul 18 '07 #3

P: n/a

[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.]

On 18 Jul, 09:29, Petr Pavlu <setupNOS...@dagobah.czwrote:
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.

Jul 21 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.