473,780 Members | 2,258 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cleanup patterns

MQ
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 example, which uses the global errno to store
the error.

#define CLEANUP(err) ({errno = (err); goto cleanup})

int example_functio n()
{
SOMETYPE * a,b,c;
errno = 0;

if(!(a = malloc(sizeof(a ))))
CLEANUP(ENOMEM) ;

if(!(b = malloc(sizeof(b ))))
CLEANUP(ENOMEM) ;

if(!(c = malloc(sizeof(c ))))
CLEANUP(ENOMEM) ;

/* do something here */

cleanup:
if(a)
free(a);
if(b);
free(b);
if(c)
free(c);
if(errno)
return -1;
return 0;
}

Nov 29 '06
69 3246
Richard Heathfield <rj*@see.sig.in validwrites:
[...]
Remember that this subthread was prompted by someone who suggested it's a
waste of time to check malloc's return value at all! Such people never ever
run out of memory, no matter how many Gigabytes of emergency reserve they
allocate. Their programs crash randomly sometimes for no apparent reason,
but at least they never run out of memory!
But the person who made this statement presented, as an alternative to
checking malloc's return value, a wrapper function that checks
malloc's return value. (Actually he presented a URL for such a
function.) Some posters here have advocated simply ignoring malloc()
failures; the poster in this thread (sorry, I don't remember who it
was) did not.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 10 '06 #41
Eric Sosman <es*****@acm-dot-org.invalidwrit es:
Keith Thompson wrote:
>Eric Sosman <es*****@acm-dot-org.invalidwrit es:
[...]
>> A fairly common strategy is to malloc() a good-sized
chunk of memory "for emergency use only," sometime during
program initialization when memory is probably plentiful.
If malloc() fails later on, you free() the emergency stash
to provide enough memory for the graceful-shutdown code to
subsist on.
The cost of this is that you can run out of memory in cases where
there would have been enough if you hadn't allocated the emergency
stash.

True. Sometimes the canary dies even though the air in
the mine is still just barely breathable.
Right. But a more apt analogy here is that you bring a *really big*
canary into the mine with you. If the miners start to have trouble
breathing, you kill the canary and release the oxygen from its
bloodstream into the air, giving the miners enough time to exit
gracefully. (Ok, maybe it's just an inflatable plastic canary.) If
the miners were just about to leave anyway, bringing the canary was a
waste of time -- just as any insurance policy that doesn't pay off is
a waste of money. (Life insurance is a really bad deal if you happen
to be immortal.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 10 '06 #42
Keith Thompson wrote:
>
.... snip ...
waste of time -- just as any insurance policy that doesn't pay off
is a waste of money. (Life insurance is a really bad deal if you
happen to be immortal.)
Now I know why I haven't had any for the past 20 years :-) (Apart
from the Social Security death 'benefit').

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Dec 11 '06 #43
rp*****@yahoo.c om (Roland Pibinger) wrote:
On Sat, 09 Dec 2006 16:42:14 +0000, Richard Heathfield wrote:
Roland Pibinger said:
<snip>
It hardly makes sense to check the return value of malloc.
It certainly doesn't make sense not to!

And what is your program supposed to do when memory is exhausted?
Depends entirely on the situation. If your word processor asks for a
large amount of memory to paste a graphic, and it doesn't get it,
putting up a message saying "sorry, no memory for graphic" is a lot more
civilised than just bombing out of the entire document. Even in the
worst case, putting up a meaningful message and exiting gracefully is
always better than crashing and burning.

Richard
Dec 11 '06 #44
rp*****@yahoo.c om (Roland Pibinger) wrote:
On Sat, 09 Dec 2006 12:47:38 -0500, CBFalconer wrote:
Consider a big sort where the
input mechanism collects records in a linked list until memory is
exhauseted, mergesorts the list, dumps it to a temporary file,
discards the list, and repeats, dumping to the next temporary
file. When the input is exhausted it mergest the set of
temporaries into an output file.

Isn't there an external mergesort?
Yes. But they're typically a lot slower than internal sorts, so you
don't use it until you _know_ that you need it. Hence the check on
malloc().

Richard
Dec 11 '06 #45
Keith Thompson said:
Richard Heathfield <rj*@see.sig.in validwrites:
[...]
>Remember that this subthread was prompted by someone who suggested it's a
waste of time to check malloc's return value at all! Such people never
ever run out of memory, no matter how many Gigabytes of emergency reserve
they allocate. Their programs crash randomly sometimes for no apparent
reason, but at least they never run out of memory!

But the person who made this statement presented, as an alternative to
checking malloc's return value, a wrapper function that checks
malloc's return value.
He did? Oh, so he did. My apologies to Mr Pilinger. Nevertheless, whilst
"detect and die" does at least beat "ignore and hope", it remains a
neophyte solution - acceptable from, say, a first-year student. I'd expect
better from a second-year.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 11 '06 #46
rp*****@yahoo.c om (Roland Pibinger) wrote:
On Sat, 09 Dec 2006 17:50:09 +0000, Richard Heathfield wrote:
Roland Pibinger said:
And what is your program supposed to do when memory is exhausted?
This is documented in the literature, and has been discussed on this
newsgroup a number of times before. See, for example:

<3D************ ***@eton.powern et.co.uk>

Those are mostly hints how to reduce the dynamic memory consumption of
a program but don't answer the question. OOM usually means that you
must terminate the application. The simplest way is a xmalloc-like
function. If enough context is available some cleanup can be done
before.
The problem with xmalloc()-like functions is that they crash anyway;
they just crash with a predictable message. This _may_ be good enough,
but IMO not nearly as often as I see it done in the wild.

Richard
Dec 11 '06 #47
"santosh" <sa*********@gm ail.comwrote:
Roland Pibinger wrote:
Not all resources are equal and need equal treatment. It hardly makes
sense to check the return value of malloc. Just use a xmalloc function
which can be found in many variants on the internet (e.g.
http://www.tug.org/tex-archive/dviwa...2xx/xmalloc.c).

Well, it's so simple that most programmers will write their own
versions of it, if need be. The code seems to use the old style
function definition and uses unsigned instead of size_t, which isn't
the way it's done now. And calling exit() with a random value is not
portable. It's better to use EXIT_FAILURE.
Not to mention that the particular random value used in this xmalloc is,
erm, rather silly, given the comment above. Don't _all_ odd values mean
some kind of success on VMS?

Richard
Dec 11 '06 #48
Bill Reid wrote:
Richard Heathfield <rj*@see.sig.in validwrote in message
news:fr******** *************** *******@bt.com. ..
MQ said:
Bill Reid wrote:
>
>For more complex functions, you'll quite often have contigent
>dependancies for each resource acquisition that don't fit neatly into
>the "nest", and the overhead of the function calling mechanism
>means that functions are not infinitely or always a "fabulous
>mechanism" for something as silly as "keeping the indent
>level down" (unless you like your "C" code to run as slow
>as "Java"!).
>
These are my greatest concerns, as I am writing file system driver code
that needs to be fast efficient.
Rule 1: if it doesn't work, it doesn't matter how fast it is.
Rule 2: it is easier to make a correct program fast than it is to make a
fast program correct.
Rule 3: it is easier to make a readable program correct than it is to make
a
correct program readable.
I think these are actually the three rules for pontificating about
programming instead of actually programming...y ears ago I read
the REAL rules for writing "correct" "fast" and "efficient" code, and
of course, as everybody who's not just pontificating knows,
it boils down to one general rule: pick the two you really want, because
a lot of times you CAN'T have all three...
And that's before we get anywhere near the Two Rules of
Micro-Optimisation.
For completeness, these are:

Rule 1: Don't do it.
Rule 2 (for experts only): Don't do it yet.
I certainly wasn't talking about anything like "micro-optimization".
I'm talking about great big gobs of "MACRO-optimization", like
slowing down or speeding up what was virtually the IDENTICAL
code by a factor of up to ten-fold (I could make the same program run
in either two seconds or 20 seconds)...
On a lot of modern CPUs the difference between a function call and a
jump (as in generated by switch or if) is nowhere near ten-fold when
compiled with an properly optimising compiler. One fold at most (note
that one-fold is ten times slower) or more typically up to 4 times
slower. Indeed on at least two architectures I code for, a function
call (if not recursive) compiles to execute in exactly the same number
of CPU cycles as a regular jump/branch.
This is not exactly an academic exercise for me, since a lot of the
code I work with takes several HOURS to run on a Pentium-class
machine, and I have to run it EVERY day.
Of course, if you're programming for an architecture as archaic and
register-starved as the Pentium then function call overhead can be an
issue. Even so, improvements have been made to x86-64 which makes the
function call overhead for x86-64 even less than before.

Dec 11 '06 #49
On Mon, 11 Dec 2006 07:41:06 GMT, Richard Bos wrote:
>The problem with xmalloc()-like functions is that they crash anyway;
they just crash with a predictable message.
They don't crash the program, they call exit (which also calls
atexit).
>This _may_ be good enough,
but IMO not nearly as often as I see it done in the wild.
In order to run your program primarily needs one resource, memory.
When it runs out of memory (e.g. due to a memory leak) there is hardly
anything you can do except to (more or less) gracefully terminate the
program. Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

Best wishes,
Roland Pibinger
Dec 11 '06 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2566
by: Design Pattern Catalog | last post by:
Thank you for your interest in "Design Patterns: Elements of Reusable Object-Oriented Design", by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. This message answers several frequently asked questions. If you thought you were asking for the source code, you must have made a mistake. Please try again! The "pattern home page", with all this information and more, is at...
6
1470
by: use dmgass at hotmail dot com | last post by:
I'm writing a module and when it is imported by a script I want some code automatically executed when the importing script is finished executing. I'd like it to execute before interactive mode is entered when executing the importing script from the command line. I don't want to have to impose that the importing script must call a function at it's end. Any help is greatly appreciated!!
32
2216
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)
1
2375
by: Jay | last post by:
The GOF text is widely considered the definitive book on the topic. Design Patterns: Elements of Reusable Object-Oriented Softare, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Note, all the examples are in C++ but you can get through them with a little work.
13
6562
by: John Salerno | last post by:
Here are a few I'm considering: Design Patterns Explained : A New Perspective on Object-Oriented Design (2nd Edition) (Software Patterns Series) by Alan Shalloway Design Patterns C# by Steven John Metsker Design Patterns by Erich Gamma Head First Design Patterns by Elisabeth Freeman
12
1912
by: Jeff | last post by:
I'm just getting up to speed on OOP patterns (e.g, MVC) and I'm wondering how closely they are followed out in the real world. Do those of you who use them try to follow them as closely as possible and deviate only as necessary? Or do you only generally follow them; mix-n-match as necessary? Just wondering what I should be looking to accomplish with OOP patterns in general. Thanks!
1
4585
by: Jason S | last post by:
I haven't used try/catch/finally very much in Javascript. My function (let's call it try_it()) needs to call a function that could throw an exception (let's call it dangerous()) with some setup() beforehand and cleanup() afterwards. What I want to make sure cleanup() is called whether or not dangerous throws an exception, and if it does throw an exception, rethrow the exception to whatever is calling try_it(). In C++ this is much easier...
7
3105
by: =?Utf-8?B?bWF2cmlja18xMDE=?= | last post by:
Hi, I would like to know more about design patterns and specifically using C#. Can any one recommend a good book? Thanks
4
2669
by: IanWright | last post by:
I've got a section of a program that I can't quite get to work. I'm fairly sure its something very simple/trivial but it looks correct to me, so if someone could help me fix the problem, and explain what it is that is wrong, that would be great... I've posted a sample of code, which is the bit of interest: class Solution { private: int *HeuristicTours; public: int* GetTours() {
0
9636
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
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10075
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
8961
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
7485
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
5373
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...
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.