473,780 Members | 2,229 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
Bill Reid wrote:
>
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.
Maybe it's time for a 64 bit upgrade!

--
Ian Collins.
Dec 11 '06 #51
rp*****@yahoo.c om (Roland Pibinger) writes:
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.
Along with a number of other resources.
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.
That's not always true; it depends on the application. Somebody
already posted an example of an interactive editor failing to allocate
enough memory to load an image; the proper response is to issue a
diagnostic and continue running, not to crash the program.
Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.
That behavior is arguably non-conforming.

--
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 11 '06 #52
Keith Thompson said:
rp*****@yahoo.c om (Roland Pibinger) writes:
> Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.
I would have no doubt about that - it's non-conforming. What I would
question is the OP's claim that Linux over-commits. It is true that it can
be configured to over-commit, but certainly my installation is not
configured that way by default.

--
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 #53
Keith Thompson wrote:
rp*****@yahoo.c om (Roland Pibinger) writes:
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.

Along with a number of other resources.
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.

That's not always true; it depends on the application. Somebody
already posted an example of an interactive editor failing to allocate
enough memory to load an image; the proper response is to issue a
diagnostic and continue running, not to crash the program.
Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.
To what standard? Linux's behaviour is outside the scope of the C
standard. Nevertheless, by never returning NULL, even when memory is
not available, it does make the malloc() implementation non-conforming.

Actually since from within the standard C program you cannot find out
_if_ memory is available or not, malloc()'s behaviour under OSes like
Linux is not non-conforming. It's doing it's job correctly, it just so
happens that it's subverted by forces outside it's control, (and the
standard's.)

Dec 11 '06 #54
santosh said:
Keith Thompson wrote:
>rp*****@yahoo.c om (Roland Pibinger) writes:
Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.

To what standard?
ISO/IEC 9899. Some people view the operating system as being part of the
implementation. This is a not unreasonable view, although it's a bit hard
on compiler-writers if they have no control over the behaviour of the OS on
their platform...

--
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 #55

Richard Heathfield wrote:
santosh said:
Keith Thompson wrote:
rp*****@yahoo.c om (Roland Pibinger) writes:

Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.
To what standard?

ISO/IEC 9899. Some people view the operating system as being part of the
implementation.
<snip>

Yes well, in that case we can add the hardware and the rest of the
physical universe as part of the implementation too.

:)

Dec 11 '06 #56
"santosh" <sa*********@gm ail.comwrites:
Richard Heathfield wrote:
>santosh said:
Keith Thompson wrote:
rp*****@yahoo.c om (Roland Pibinger) writes:

Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.

To what standard?

ISO/IEC 9899. Some people view the operating system as being part of the
implementation .
<snip>

Yes well, in that case we can add the hardware and the rest of the
physical universe as part of the implementation too.

:)
Yes.

An implementation that doesn't meet the requirements of the standard
is non-conforming. Having a good excuse for the non-conformance
doesn't make it conforming.

--
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 11 '06 #57
Richard Bos wrote:
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().
The relative slowness is because the external sort is primarily
dependant on the i/o processing. You can get remarkable
performance by minimizing that i/o. See Wirths "Algorithms + Data
Structures = Programs" for polyphase sort. Triggering virtual
memory operation will foul that up quite nicely.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Dec 11 '06 #58
Roland Pibinger wrote:
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.
Not so. I gave an example (external sort) upthread. To misquote
Dan Pop, engage brain before aborting.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Dec 11 '06 #59
santosh wrote:
Keith Thompson wrote:
>rp*****@yahoo.c om (Roland Pibinger) writes:
.... snip ...
>>
>>Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.

That behavior is arguably non-conforming.

To what standard? Linux's behaviour is outside the scope of the C
standard. Nevertheless, by never returning NULL, even when memory
is not available, it does make the malloc() implementation
non-conforming.

Actually since from within the standard C program you cannot find
out _if_ memory is available or not, malloc()'s behaviour under
OSes like Linux is not non-conforming. It's doing it's job
correctly, it just so happens that it's subverted by forces
outside it's control, (and the standard's.)
Again, not necessarily. There is no speed requirement, so an OS
can simply postpone program execution until the memory is actually
available. Implementing this could run into the deadly embrace
problem.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Dec 11 '06 #60

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
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
9931
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
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
6727
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.