473,898 Members | 2,767 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cleanup code & malloc wrapper

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(sta ck)
return 1
}
push(stack, fclose, filepointer1)

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

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

...

if (something failed) {
execute_all(sta ck)
return 4
}

execute_all(sta ck)
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(sta ck) and return X could be defined as
#define RETURN(stack, rv) \
execute_all(sta ck) \
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
3 3626
On Wednesday 18 Jul 2007 1:59 pm, in comp.lang.c, Petr Pavlu
<se*********@da gobah.czwrote:
Message ID: <f7**********@n s.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(sta ck)
return 1
}
push(stack, fclose, filepointer1)

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

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

...

if (something failed) {
execute_all(sta ck)
return 4
}

execute_all(sta ck)
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(sta ck) and return X could be defined as
#define RETURN(stack, rv) \
execute_all(sta ck) \
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
>On Wednesday 18 Jul 2007 1:59 pm, in comp.lang.c, Petr Pavlu
><se*********@d agobah.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_FAILU RE) or similar.]

In article <f7**********@a ioe.orgsantosh <sa*********@gm ail.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_FAILU RE); /* or exit(exit_on_fa ilure), 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 *unconditionall y* 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 (40°39.22'N, 111°50.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

[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...@da gobah.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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1528
by: Julie | last post by:
(I searched the FAQ, but didn't find anything relevant -- if there is, please post a link.) Is there a design paradigm that indicates that a class that manages an external resource should automatically perform clean up in the destructor? For example, suppose the following file-wrapper class. // begin
54
7886
by: Neo | last post by:
Hi Folks, I've a simple qestion related to dynamic memory allocation in C here is the code: #include <stdio.h> int main() {
32
2229
by: fatted | last post by:
I've written a function (clean_string) to remove characters from a string, but it looks clunky to me, and I'm sure there's a more 'C' like way of doing it (still learning), comments and advice welcome... -- #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void)
9
1747
by: Mark Stijnman | last post by:
I need to use an API in our current project and I have been writing some wrapper classes for the functionality we need. Unfortunately, before you can use any API calls, the API must be initialized, and after your done with the API, it wants you to call a cleanup function. I am now looking for a safe solution to wrap the API initialization/cleanup. I am thinking of something along these lines: every class that needs the API is privately...
16
2340
by: Pedro Graca | last post by:
I have a file with different ways to write numbers ---- 8< (cut) -------- 0: zero, zilch,, nada, ,,,, empty , void, oh 1: one 7: seven 2: two, too ---- >8 -------------- I wanted to read that file and put it into dynamic memory, like
5
37172
by: sunny | last post by:
Hi All Is there any way to determine stack and heap size, during runtime. i.e can we predict stack overflow. etc
69
3270
by: MQ | last post by:
Hi all I am just wondering how most people implement cleanup in C functions. In particular, if the function opens a number of resources, these need to be released properly should an error occur at any point in the function (as well as at the end if successful). C++ has exceptions, the only way I can see to do this neatly in C is to use goto statements. Is my method of implementing cleanup good, or are their better ways. Here is an...
318
13189
by: jacob navia | last post by:
Rcently I posted code in this group, to help a user that asked to know how he could find out the size of a block allocated with malloc. As always when I post something, the same group of people started to try to find possible errors, a harmless passtime they seem to enjoy. One of their remarks was that I used "int" instead of "size_t" for the input of my allocator function.
55
3348
by: lovecreatesbea... | last post by:
Do you check all error conditions for all library calls in you code? Is it necessary to check all errors? Is it convenient to check all errors (or how to make code clean and readable with mass of non business logic related code block)? The following code from net-snmp library calls atoi five times but checks none. Do we code a wrapper my_atoi_with_error_check() around atoi and call this new one everywhere else? Is it a good practice...
0
9993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10946
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10481
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9658
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8034
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5877
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6076
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4705
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.