473,769 Members | 2,348 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 3241
CBFalconer wrote:
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 :-)
Because you're immortal? Wow.
(Apart
from the Social Security death 'benefit').

I have some freebie insurance from work, some multiplier times your
yearly salary.

Brian
Dec 11 '06 #61
"Default User" <de***********@ yahoo.comwrites :
CBFalconer wrote:
>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 :-)

Because you're immortal? Wow.
So far ...

--
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 #62
Keith Thompson wrote:
"Default User" <de***********@ yahoo.comwrites :
>CBFalconer wrote:
>>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 :-)

Because you're immortal? Wow.

So far ...
Well, I only have experience to go by, and so far there have been
no exceptions. I've had a couple of near misses lately though. Is
this an omen? Maybe we need an ISO standard for reference.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Dec 11 '06 #63
rp*****@yahoo.c om (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).
To the end user, it's usually all the same.
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)
Well, _yes_. If you assume rampant bug that no C programmer should let
into a production program any more (and, therefore, some famous
companies regularly do), you might as well terminate the program there
and then. In fact, why not be pro-active, and terminate it at random
intervals?
there is hardly anything you can do except to (more or less)
gracefully terminate the program.
As shown upthread, for a _well written_ program, this is simply untrue.
It _may_ be the case, but often you have better options.
Not even that is always possible since some OS (IIRC, Linux)
never return NULL for malloc even when memory is exhausted.
Those OSes are broken. If you can't trust your OS not to lie to you, why
trust your computer at anything?

Richard
Dec 12 '06 #64
On Mon, 11 Dec 2006 09:30:03 GMT, Keith Thompson wrote:
>That behavior is arguably non-conforming.
<offtopic>
When Linux Runs Out of Memory
http://www.linuxdevcenter.com/lpt/a/6808
</offtopic>
Dec 16 '06 #65
Roland Pibinger wrote:
On Mon, 11 Dec 2006 09:30:03 GMT, Keith Thompson wrote:
>That behavior is arguably non-conforming.

<offtopic>
When Linux Runs Out of Memory
http://www.linuxdevcenter.com/lpt/a/6808
</offtopic>
<offtopic>
http://lwn.net/Articles/104179/
</offtopic>

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 16 '06 #66
Eric Sosman wrote
(in article <P8************ *************** ***@comcast.com >):
http://lwn.net/Articles/104179/
OT, Perhaps. Hilarious? Definitely.

Over-engineering a solution to a problem that doesn't even need
to exist.

--
Randy Howard (2reply remove FOOBAR)
"The power of accurate observation is called cynicism by those
who have not got it." - George Bernard Shaw

Dec 16 '06 #67

sl*******@yahoo .com <sl*******@gmai l.comwrote in message
news:11******** **************@ 79g2000cws.goog legroups.com...
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)
OK, I'm officially confused...I specifically said "two seconds or 20
seconds" as being "ten-fold" (as in, a thousand is a hundred "ten-fold"),
then you re-define "fold" as "ten times slower". So what you're saying
is that with a "properly optimising compiler", a function call is UP TO
"ten times slower"...which is basically what I was always told, it takes
somewhere around 4-8 extra cycles as overhead for a function call,
so I think we don't have a disagreement there?
or more typically up to 4 times
slower.
"6" was the magic number I was told (or actually read) to work with...
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 may be true, and I don't doubt that it depends on the specific
function call and optimization "tricks" of the compiler in any event...
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.
Yeah, slam the Pentium, then go ahead and slam "MIPS" and "SPARC"
while you're at it, since I've been able to significantly speed up or slow
down programs on all of them (in many cases, the exact same program
on all the different architectures).
Even so, improvements have been made to x86-64 which makes the
function call overhead for x86-64 even less than before.
I will admit that the ever-increasing power and speed of computer
hardware does make a lot of these considerations practically moot...but
that still doesn't excuse how I saw people coding back when it made
a TREMENDOUS practical difference, and these WERE what had
to be considered the elite systems software engineers in the entire
world...

---
William Ernest Reid

Dec 29 '06 #68

Ian Collins <ia******@hotma il.comwrote in message
news:4u******** *****@mid.indiv idual.net...
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!
Then I'll re-write it all in Java!

---
William Ernest Reid

Dec 29 '06 #69
Bill Reid wrote:
sl*******@yahoo .com <sl*******@gmai l.comwrote in message
news:11******** **************@ 79g2000cws.goog legroups.com...
Bill Reid wrote:
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)

OK, I'm officially confused...I specifically said "two seconds or 20
seconds" as being "ten-fold" (as in, a thousand is a hundred "ten-fold"),
then you re-define "fold" as "ten times slower".
Sorry, I was confusing "fold" with "orders of magnitude". Fold, proper,
commonly means multiplication by that factor which makes what you said
correct and what I said wrong.
or more typically up to 4 times
slower.

"6" was the magic number I was told (or actually read) to work with...
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 may be true, and I don't doubt that it depends on the specific
function call and optimization "tricks" of the compiler in any event...
On a lot of modern architectures (this excludes x86-32 although it
includes x86-64) this is quite trivial (see below).
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.
I will admit that the ever-increasing power and speed of computer
hardware does make a lot of these considerations practically moot...but
The point is not the speed of the hardware. No matter how fast the
hardware becomes a ten fold slowdown is STILL a ten fold slowdown. The
point is that x86-64 is not register starved allowing the compiler to
avoid using stacks to pass parameters and especially for the kind of
trivial functions we were discussing can also allow the compiler to do
*nothing* to pass parameters via overlays.

Hence for the kinds of functions we're discussing (small utility
functions to reduce indentation, remember that we're not discussing
function calling *in general*) passing parameters can be optimised to
generate zero instructions and calling the function itself generates
one instruction. On most modern machines that instruction takes the
same amount of time to execute as a conditional branch.
that still doesn't excuse how I saw people coding back when it made
a TREMENDOUS practical difference, and these WERE what had
to be considered the elite systems software engineers in the entire
world...
And now we have the conclusion. Your trick programming and inlining
WERE useful in the age of dino-mainframes where workstation CPUs were
nothing more than glorified microcontroller s. Today even lowly 50 cent
microcontroller s don't break a sweat executing deeply nested function
calls (unless you're doing something silly like directly generating
video signals on output pins without the help of graphics hardware).

Dec 30 '06 #70

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

Similar topics

2
2565
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
2210
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
2374
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
6561
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
4584
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
2667
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
9586
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
10210
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...
1
9990
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,...
1
7406
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
6672
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
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
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
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
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.