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

Why leave the error handling to the caller?

P: n/a
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}

They then go on to say

"strdup passes that value on, leaving error-handling to its caller"

Why leave the error-handling to it's caller? Couldn't a person go like

char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}
Chad

Jun 17 '07 #1
Share this Question
Share on Google+
94 Replies


P: n/a
Chad wrote:
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}

They then go on to say

"strdup passes that value on, leaving error-handling to its caller"

Why leave the error-handling to it's caller? Couldn't a person go like

char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}
Chad
Exiting the program is not the only possibility here.
The function has no way to know what the general context is, and can't
decide what is the best thing to do.

For starters, I would NOT like that I risk that a library routine
exits my program without any possibility for me to avoid this
or to take an alternative course of action.
Jun 17 '07 #2

P: n/a
Chad said:
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}
Better:

#include <stdlib.h>
#include <string.h>

char *dupstr(const char *s)
{
size_t len = strlen(s) + 1;
char *p = malloc(len);
if(p != NULL)
{
memcpy(p, s, len);
}
return p;
}
>
They then go on to say

"strdup passes that value on, leaving error-handling to its caller"

Why leave the error-handling to it's caller?
Because it is not a library function's job to make that kind of
decision. A library function should do what it is supposed to do or
explain why it can't, and *nothing else*. The decision to abend a
program is not the library's to make.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 17 '07 #3

P: n/a

"Chad" <cd*****@gmail.comwrote in message
news:11**********************@p77g2000hsh.googlegr oups.com...
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}

They then go on to say

"strdup passes that value on, leaving error-handling to its caller"

Why leave the error-handling to it's caller? Couldn't a person go like

char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}

There quite a strong case for a safemalloc() library function that does
terminate with an error message on fail. However we don't have it.

Another problem is vandalism of stderr. Microsoft do this. The call
executes, but no error message appears. Which means that stderr is useless
in portable routines.

More modern languages have exception handling, which is the best solution,
in the right hands. The program will terminate with an error message, unless
the caller catches the exception. However in practise inexperienced people
often make a real hash of exceptions, usually by catching too many too low,
or throwing oddballs like "negative root error" where they meant "illegal
argument", or sometimes by using them for non-error flow control.

So we are stuck with handling out of memory conditions by freeing and
returning an error code, which usually means that caller has to to the same,
until eventually control reaches a high level routine which has access to
the user interface.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 17 '07 #4

P: n/a
Malcolm McLean said:

<snip>
There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.
No, there isn't. Library routines have no business deciding to terminate
the program.
Another problem is vandalism of stderr. Microsoft do this. The call
executes, but no error message appears.
Not so. In their hosted environment, stderr is handled correctly. And in
their freestanding environment, they don't have to support it at all.
So we are stuck with handling out of memory conditions by freeing and
returning an error code, which usually means that caller has to to the
same, until eventually control reaches a high level routine which has
access to the user interface.
In other words, decision-making power is where it belongs - in the hands
of the programmer.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 17 '07 #5

P: n/a
>Why leave the error-handling to it's caller? Couldn't a person go like
>
char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}
I certainly don't want to fly on any airplanes where you wrote the
flight control programs.

I would also be very annoyed if attempting to paste a large document
into the current one caused the editor to exit without giving me a
chance to save the old one, even if the paste failed due to lack
of memory.

There is the problem that a low-level routine does not know how to
handle errors. If it needs to interact with the user, how should
it do it? Text out stderr? (might not be visible) An X window
popup? A Microsoft Window popup?
Jun 17 '07 #6

P: n/a
Op Sun, 17 Jun 2007 09:06:39 -0700 schreef Chad:
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}
Get a newer edition: K&R2 doesn't even mention strdup. With reason, see
elsethread.
--
Coos
Jun 17 '07 #7

P: n/a
Op Sun, 17 Jun 2007 20:47:19 +0200 schreef Coos Haak:
Op Sun, 17 Jun 2007 09:06:39 -0700 schreef Chad:
>On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}
Get a newer edition: K&R2 doesn't even mention strdup. With reason, see
elsethread.
It was not in the index, but the same definition now is placed at the top
of page 143 ;-(
--
Coos
Jun 17 '07 #8

P: n/a
Chad wrote:
On to top of page 163 in the book "The C Programming Langauge" by K &
R, they have the following:

char *strdup(char *s)
{
char *p;
p=(char *)malloc(strlen(s)+1);
if( p != NULL)
strcpy(p,s):
return p;
}

They then go on to say

"strdup passes that value on, leaving error-handling to its caller"

Why leave the error-handling to it's caller? Couldn't a person go like

char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}
Chad
The only possible other solution would be to pass an error handling
function, something like this:

char *strdup(char *s,int (*errorHandler)(size_t request,void *arg),void
*arg)

And thereby allowing the programmer to write their own error handler
returning further instructions to the strdup function like fail or
retry. Allowing the function to be NULL and in that case display a
diagnostic message and terminate.
I do however *not* think that this would be a generally better solution.
Jun 17 '07 #9

P: n/a

"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com...
Malcolm McLean said:

<snip>
>There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to terminate
the program.
The problem is that the code is disproprtionate. Let's say I want to set up
a structure with a list of strings.

typedef struct
{
char **str;
int N;
} STRINGS;

STRINGS *strings(char *data)
{
STRINGS *answer;
char *ptr, *next;
int i;

answer = malloc(sizeof(STRINGS));
if(!answer)
goto error_exit;
answer->str = 0;
answer->N = strcount(data, ',');
if(!answer->N)
return answer;
answer->str = malloc(answer->N * sizeof(char *));
if(!answer->str)
goto error_exit;
for(i=0;i<answer->N;i++)
answer->str[i] = 0;
ptr = data;
for(i=0;i<answer->N;i++)
{
next = strchr(ptr, ',');
if(!next)
next = ptr + strlen(ptr);
answer->str[i] = malloc(len + 1);
if(!answer->str[i])
goto error_exit;
stncpy(answer->str[i], len, ptr);
answer->str[len] = 0;
ptr = next + 1;
}
return answer;
error_exit:
killstrings(answer);
return 0;
}

void killstrings(STRINGS *s)
{
int i;

if(s)
{
if(s->str)
{
for(i=0;i<s->N;i++)
free(s->str[i]);
}
free(s->str);
free(s);
}
}

Now that is about as simple as an arbitrary dataset is likely to be - just
an array of strings. I counted 14 lines purely to handle malloc() failures.
The code is untested and there is probably something wrong with it. There
are all sorts of gotchas. For instance the 14 lines include code to
initialise all the pointers to zero so that the kill function doesn't crash
when it tries to free them, N has to be tested for zero because malloc()
might return 0, though in fact it is probably not sensible to call with a
empty set. Actually looking over it I can see an error in the way I count
the strings in the input, easy to do because the logic is lost in error
handling code that is unlikely ever to be called in real use.

To my mind this is a very serious disadvantage of the "caller handles error"
paradigm.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 17 '07 #10

P: n/a
Chad wrote:
Why leave the error-handling to it's caller? Couldn't a person go like

char *strdup(char *s)
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
You might want strdup to be a function
that you can use in different situations,
where you have another option besides exit,
for when malloc returns a null pointer value.

--
pete
Jun 17 '07 #11

P: n/a
Malcolm McLean wrote:
>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com...
>Malcolm McLean said:

<snip>
>>There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to terminate
the program.
The problem is that the code is disproprtionate. [...]
[code snipped; see up-thread]

Now that is about as simple as an arbitrary dataset is likely to be -
just an array of strings. I counted 14 lines purely to handle malloc()
failures.
Line counts in code that won't even compile aren't all
that persuasive.

But even so: I counted 58 lines in all. If you expended
*no* lines on error-checking you'd still have 44. The Sixth
Commandment envisions a ratio of two lines of error-handling
per line of payload ("yea, even though the checks triple the
size of thy code"), so why are you complaining about a rate
less than one-twelfth as great? The Commandment describes an
extreme circumstance, true, but instructs the Righteous to be
prepared to work at least twelve times as hard as you do.
To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.
The "serious disadvantage" seems to be that it makes lazy
programmers work harder than they'd like to.

If you require every "leaf" function to do its own error-
handling, you defeat reusability. Nice little function here
that does something my program needs -- oh, too bad, can't
use it because the actions it takes on error don't mesh with
my program's strategy. Contrast with a function that informs
its caller "Sorry; couldn't do it" and allows the caller to
decide what to do next in light of its greater understanding
of overall context -- it's the latter function that can be
reused, not the former.

Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?

--
Eric Sosman
es*****@acm-dot-org.invalid
Jun 17 '07 #12

P: n/a

"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
news:HY******************************@comcast.com. ..
Malcolm McLean wrote:
>>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com...
>>Malcolm McLean said:

<snip>

There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to terminate
the program.
The problem is that the code is disproprtionate. [...]
[code snipped; see up-thread]

Now that is about as simple as an arbitrary dataset is likely to be -
just an array of strings. I counted 14 lines purely to handle malloc()
failures.

Line counts in code that won't even compile aren't all
that persuasive.

But even so: I counted 58 lines in all. If you expended
*no* lines on error-checking you'd still have 44. The Sixth
Commandment envisions a ratio of two lines of error-handling
per line of payload ("yea, even though the checks triple the
size of thy code"), so why are you complaining about a rate
less than one-twelfth as great? The Commandment describes an
extreme circumstance, true, but instructs the Righteous to be
prepared to work at least twelve times as hard as you do.
>To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.

The "serious disadvantage" seems to be that it makes lazy
programmers work harder than they'd like to.

If you require every "leaf" function to do its own error-
handling, you defeat reusability. Nice little function here
that does something my program needs -- oh, too bad, can't
use it because the actions it takes on error don't mesh with
my program's strategy. Contrast with a function that informs
its caller "Sorry; couldn't do it" and allows the caller to
decide what to do next in light of its greater understanding
of overall context -- it's the latter function that can be
reused, not the former.

Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?
The Turing machine has run out of tape. That's a different kind of problem
to the others you have described.
Jun 17 '07 #13

P: n/a

"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
But even so: I counted 58 lines in all. If you expended
*no* lines on error-checking you'd still have 44. The Sixth
Commandment envisions a ratio of two lines of error-handling
per line of payload ("yea, even though the checks triple the
size of thy code"), so why are you complaining about a rate
less than one-twelfth as great? The Commandment describes an
extreme circumstance, true, but instructs the Righteous to be
prepared to work at least twelve times as hard as you do.
Here's a class with exactly the same functionality written in Java. This
time I compiled it.

class Strings
{
String[] str;
public Strings(String data)
{
int i;
int start = 0;
int end = 0;
int N = 1;

for(i=0;i<data.length();i++)
if(data.charAt(i) == ',')
N++;
str = new String[N];
for(i=0;i<N;i++)
{
start = end;
end = data.indexOf(',', start+1);
if(end == -1)
end = data.length();
if(start != 0)
start = start + 1;
str[i] = data.substring(start, end);
}
}
}

It is much shorter and easier to follow, purely because Java does your
memory management for you. The string functions are different but very
comparable. One big difference is that we no longer need a kill function,
but even excluding that, the removal of the need to check malloc() is a real
advantage.
>To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.

The "serious disadvantage" seems to be that it makes lazy
programmers work harder than they'd like to.
Exactly. It would be nice to live in a world with no deadlines and no money
where efficiency didn't matter. Some countries are like that. But not
Britain.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 17 '07 #14

P: n/a
Malcolm McLean wrote, On 17/06/07 22:40:
>
"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
news:HY******************************@comcast.com. ..
>Malcolm McLean wrote:
>>>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com.. .
Malcolm McLean said:

<snip>

There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to
terminate
the program.

The problem is that the code is disproprtionate. [...]
[code snipped; see up-thread]
<snip>
> Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?
The Turing machine has run out of tape. That's a different kind of
problem to the others you have described.
It is a recoverable error in many situations just as all the others are.
For example, when stressing my company notebook several times I've had
VMware tell me it was out of memory giving the option to retry. I closed
down some other stuff, told it to retry, and continued with my work. Far
better than your approach of having it die on me.
--
Flash Gordon
Jun 17 '07 #15

P: n/a
In article <R8*********************@bt.com>,
Malcolm McLean <re*******@btinternet.comwrote:
>The Turing machine has run out of tape. That's a different kind of problem
to the others you have described.
Of course it's a different kind of problem: it would mean that you've
reached the end of infinity, probably having forgotten to save some
Scotch to find out whether infinite aging makes Scotch infinitely better.
--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us. -- Ecclesiastes
Jun 17 '07 #16

P: n/a
Malcolm McLean wrote:
[...]
Here's a class with exactly the same functionality written in Java.
Good-oh. Got a COBOL version, too?
This time I compiled it.
A wise precaution.
It is much shorter and easier to follow, purely because Java does your
memory management for you. [...]
Note, too, that Java uses exactly the pattern you despise:
It leaves the question of how to recover from an error up to
the invoker. If the JVM runs out of memory, it does *not*
just throw your program down the nearest oubliette. Instead,
it throws and OutOfMemoryError -- which the caller can catch,
if it wants, and then take restorative measures. Pray explain
just how this supports your position that error handling should
be the prerogative of the low-level mechanisms and not of the
agency that invokes them.

You have shot your own foot.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jun 18 '07 #17

P: n/a
On Jun 17, 10:48 am, gordonb.be...@burditt.org (Gordon Burditt) wrote:
Why leave the error-handling to it's caller? Couldn't a person go like
char *strdup(char *s)
{
char *p;
if (p=(char *)malloc(strlen(s)+1) == NULL)
exit(1);
else
strcpy(p,s):
return p;
}

I certainly don't want to fly on any airplanes where you wrote the
flight control programs.
During my Mechanical Engineering days, ALL of my design work passed
through the Senior Engineer and Chief Scientist. I'm pretty sure that
if I wrote the flight control programs, my design work would go
through a similar process. And I'm pretty sure that if I made some
bonedheaded coding error, someone would catch it. And after they
caught it, I would probably hear "Chad, if your ever make that kind of
error again, we will have to find someone else that can do the job."

For the record, I did make one semi critical error on a design project
when working as a Mechanical Engineer. My manager at work told me "I
don't like having the Chief Scientist tell me there was a calculation
error. Chad, if you can't handle this type of work, I'm going to have
to find someone that can handle it."

I would also be very annoyed if attempting to paste a large document
into the current one caused the editor to exit without giving me a
chance to save the old one, even if the paste failed due to lack
of memory.
I remember back when I was connecting to the Universities computers
via dial up modem from my parents house. There was an unamed editor
that on the universities systems that exhibited this kind of behavior.
There is the problem that a low-level routine does not know how to
handle errors. If it needs to interact with the user, how should
it do it? Text out stderr? (might not be visible) An X window
popup? A Microsoft Window popup?
I don't do Micrsoft Windows.

Jun 18 '07 #18

P: n/a
Malcolm McLean said:
>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com...
>Malcolm McLean said:

<snip>
>>There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to
terminate the program.
The problem is that the code is disproprtionate.
If you try hard enough, the code /can/ be disproportionate.
Let's say I want to set up a structure with a list of strings.
I looked at your code, and found it lacking in any significant evidence
that you are a regular clc subscriber.

<snip>
Now that is about as simple as an arbitrary dataset is likely to be -
just an array of strings. I counted 14 lines purely to handle malloc()
failures.
Get back to me when you've written it properly.
The code is untested and there is probably something wrong with it.
You'd be amazed. Still, look on the bright side - it didn't actually
call gets().
To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.
To my mind it was just a bunch of broken code.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 18 '07 #19

P: n/a
"Malcolm McLean" <re*******@btinternet.comwrote:
"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?
The Turing machine has run out of tape. That's a different kind of problem
to the others you have described.
IYAM running out of disk space is closer to a Turing machine running out
of space than running out of working memory, so please explain why that
argument does not go for fopen().

More importantly, though, explain why it's such a good idea to destroy
half an hour's typing work just because you do not have the memory to
paste a big graphic into the letter.

Richard
Jun 18 '07 #20

P: n/a
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <R8*********************@bt.com>,
Malcolm McLean <re*******@btinternet.comwrote:
The Turing machine has run out of tape. That's a different kind of problem
to the others you have described.

Of course it's a different kind of problem: it would mean that you've
reached the end of infinity, probably having forgotten to save some
Scotch to find out whether infinite aging makes Scotch infinitely better.
No. It's asymptotic, but to an asymptote that varies with the brand and
variety.

Richard
Jun 18 '07 #21

P: n/a
Walter Roberson wrote:
In article <R8*********************@bt.com>,
Malcolm McLean <re*******@btinternet.comwrote:
>>The Turing machine has run out of tape. That's a different kind of problem
to the others you have described.

Of course it's a different kind of problem: it would mean that you've
reached the end of infinity, probably having forgotten to save some
Scotch to find out whether infinite aging makes Scotch infinitely better.
So ... this Turing machine runs on Scotch tape?

Good for sticky problems, then.

--
Hewlett-Packard Limited registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England

Jun 18 '07 #22

P: n/a
Chris Dollin <ch**********@hp.comwrote:
So ... this Turing machine runs on Scotch tape?
Good for sticky problems, then.
Careful; puns like that can lead to UB, especially on Mondays.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jun 18 '07 #23

P: n/a

"Richard Bos" <rl*@hoekstra-uitgeverij.nlwrote in message
news:46***************@news.xs4all.nl...
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
>In article <R8*********************@bt.com>,
Malcolm McLean <re*******@btinternet.comwrote:
>The Turing machine has run out of tape. That's a different kind of
problem
to the others you have described.

Of course it's a different kind of problem: it would mean that you've
reached the end of infinity, probably having forgotten to save some
Scotch to find out whether infinite aging makes Scotch infinitely better.

No. It's asymptotic, but to an asymptote that varies with the brand and
variety.
My sister has a wonderful saying.

Why value smoothness? Why not value fire?
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Jun 19 '07 #24

P: n/a

"Flash Gordon" <sp**@flash-gordon.me.ukwrote in message
news:4b************@news.flash-gordon.me.uk...
Malcolm McLean wrote, On 17/06/07 22:40:
>>
"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
news:HY******************************@comcast.com ...
>>Malcolm McLean wrote:

"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com. ..
Malcolm McLean said:
>
<snip>
>
>There quite a strong case for a safemalloc() library function that
>does terminate with an error message on fail.
>
No, there isn't. Library routines have no business deciding to
terminate
the program.
>
The problem is that the code is disproprtionate. [...]
[code snipped; see up-thread]

<snip>
>> Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?
The Turing machine has run out of tape. That's a different kind of
problem to the others you have described.

It is a recoverable error in many situations just as all the others are.
For example, when stressing my company notebook several times I've had
VMware tell me it was out of memory giving the option to retry. I closed
down some other stuff, told it to retry, and continued with my work. Far
better than your approach of having it die on me.
But what if you don't have a program at all because with the 33:67 payload
to malloc recovery ratio, it costs too much to write?

Sometimes it's an issue, sometimes not. If you are writing Microsoft's next
OS you have practially infinite resources. If you're knocking up a game on a
tight budget, it is no good missing Christmas. If it crashes out one every
hundred hours of gameplay, that's not ideal but it isn't the end of the
world either. If it is two months late it might be canned, then you get zero
royalties, and no-one will ever play it.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 19 '07 #25

P: n/a
Malcolm McLean wrote, On 19/06/07 20:37:
>
"Flash Gordon" <sp**@flash-gordon.me.ukwrote in message
news:4b************@news.flash-gordon.me.uk...
>Malcolm McLean wrote, On 17/06/07 22:40:
>>>
"Eric Sosman" <es*****@acm-dot-org.invalidwrote in message
news:HY******************************@comcast.co m...
Malcolm McLean wrote:
>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com.. .
>Malcolm McLean said:
>>
><snip>
>>
>>There quite a strong case for a safemalloc() library function that
>>does terminate with an error message on fail.
>>
>No, there isn't. Library routines have no business deciding to
>terminate
>the program.
>>
The problem is that the code is disproprtionate. [...]
[code snipped; see up-thread]

<snip>
>>> Should fprintf() halt the program on an I/O error?

Should fopen() halt the program if unable to open the file?

Should strtod() halt the program on a malformed input?

Then why should malloc() halt the program on a whim?

The Turing machine has run out of tape. That's a different kind of
problem to the others you have described.

It is a recoverable error in many situations just as all the others
are. For example, when stressing my company notebook several times
I've had VMware tell me it was out of memory giving the option to
retry. I closed down some other stuff, told it to retry, and continued
with my work. Far better than your approach of having it die on me.
But what if you don't have a program at all because with the 33:67
payload to malloc recovery ratio, it costs too much to write?
That's rubbish according to your own attempt at showing how bad the
ratio is.
Sometimes it's an issue, sometimes not. If you are writing Microsoft's
next OS you have practially infinite resources.
That's rubbish because the above situation is on a modern (only a couple
of months old) medium to high spec notebook.

On my previous company notebook which was high spec at the time I would
also run out of resources.

I've seen servers run out of resources, including high spec ones.
If you're knocking up a
game on a tight budget, it is no good missing Christmas. If it crashes
out one every hundred hours of gameplay, that's not ideal but it isn't
the end of the world either. If it is two months late it might be
canned, then you get zero royalties, and no-one will ever play it.
If it crashes too often because it is badly written no one will buy it.
In one extreme case a game got canned because after it was produced they
found it contained a virus, so there they lost a lot more money. I'm
sure others have failed to make it to market, or failed to have
significant sales, due to too many bugs.
--
Flash Gordon
Jun 19 '07 #26

P: n/a

"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:ur*********************@bt.com...
Malcolm McLean said:
>>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com...
>>Malcolm McLean said:

<snip>

There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to
terminate the program.
The problem is that the code is disproprtionate.

If you try hard enough, the code /can/ be disproportionate.
>Let's say I want to set up a structure with a list of strings.

I looked at your code, and found it lacking in any significant evidence
that you are a regular clc subscriber.

<snip>
>Now that is about as simple as an arbitrary dataset is likely to be -
just an array of strings. I counted 14 lines purely to handle malloc()
failures.

Get back to me when you've written it properly.
>The code is untested and there is probably something wrong with it.

You'd be amazed. Still, look on the bright side - it didn't actually
call gets().
>To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.

To my mind it was just a bunch of broken code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char **str;
int N;
} STRINGS;

STRINGS *makestrings(char *data);
void killstrings(STRINGS *s);

/*
take a comma-separated list of strings, and create
structure with separate strings.
Params: data - the input
Returns: strings object
*/
STRINGS *makestrings(char *data)
{
STRINGS *answer;
char *ptr, *next;
size_t len;
int i;

answer = malloc(sizeof(STRINGS));
if(!answer) /* 1 */
goto error_exit; /* 2 */
answer->str = 0; /* 3 */
answer->N = 1;
for(i=0;data[i];i++)
if(data[i] == ',')
answer->N++;
if(!answer->N) /* 4 */
return answer; /* 5 */
answer->str = malloc(answer->N * sizeof(char *));
if(!answer->str) /* 6 */
goto error_exit; /* 7 */
for(i=0;i<answer->N;i++) /* 8 */
answer->str[i] = 0; /* 9 */
ptr = data;
for(i=0;i<answer->N;i++)
{
next = strchr(ptr, ',');
if(!next)
next = ptr + strlen(ptr);
len = next - ptr;
answer->str[i] = malloc(len + 1);
if(!answer->str[i]) /* 10 */
goto error_exit; /* 11 */

strncpy(answer->str[i], ptr, len);
answer->str[i][len] = 0;
ptr = next + 1;
}
return answer;
error_exit: /* 12 */
killstrings(answer); /* 13 */
return 0; /* 14 */
}

/*
strings object destructor
*/
void killstrings(STRINGS *s)
{
int i;

if(s)
{
if(s->str)
{
for(i=0;i<s->N;i++)
free(s->str[i]);
}
free(s->str);
free(s);
}
}

int main(int argc, char **argv)
{
STRINGS *str;
int i;

if(argc < 2)
{
printf("Call with comma-separated list of strings\n");
exit(EXIT_FAILURE);
}
str = makestrings(argv[1]);
for(i=0;i<str->N;i++)
printf("***%s***\n", str->str[i]);
return 0;
}

Here's a compileable version. I haven't tested for malloc() failures, so not
all the code has actually been exectuted, and it is not easy to do that. My
free Microsoft compiler demanded a reregistration.

For what it is worth I have started a new project - BabyX. It's a
lightweight toolkit built on top of xlib to free me from MS.

Jun 19 '07 #27

P: n/a
Malcolm McLean wrote:
>
.... snip ...
>
But what if you don't have a program at all because with the 33:67
payload to malloc recovery ratio, it costs too much to write?

Sometimes it's an issue, sometimes not. If you are writing
Microsoft's next OS you have practially infinite resources. If
you're knocking up a game on a tight budget, it is no good missing
Christmas. If it crashes out one every hundred hours of gameplay,
that's not ideal but it isn't the end of the world either. If it is
two months late it might be canned, then you get zero royalties,
and no-one will ever play it.
Are you crippled? Write your own:

#include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 19 '07 #28

P: n/a
CBFalconer wrote On 06/19/07 17:36,:
Malcolm McLean wrote:

... snip ...
>>But what if you don't have a program at all because with the 33:67
payload to malloc recovery ratio, it costs too much to write?

Sometimes it's an issue, sometimes not. If you are writing
Microsoft's next OS you have practially infinite resources. If
you're knocking up a game on a tight budget, it is no good missing
Christmas. If it crashes out one every hundred hours of gameplay,
that's not ideal but it isn't the end of the world either. If it is
two months late it might be canned, then you get zero royalties,
and no-one will ever play it.


Are you crippled? Write your own:

#include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
if (!(t = malloc(sz)) && sz 0) ...
return t;
}

Very complex. Will never return NULL.
Jun 19 '07 #29

P: n/a
"Eric Sosman" <Er*********@sun.comwrote in message
news:1182292165.934849@news1nwk...
CBFalconer wrote On 06/19/07 17:36,:
> if (!(t = malloc(sz))) exit(EXIT_FAILURE);
....
>Very complex. Will never return NULL.

if (!(t = malloc(sz)) && sz 0) ...
That cure is almost as bad as the cause, since it violates the
(informal)documentation given.

#include <stdlib.h>
/* like malloc(), but never returns NULL */
void *xmalloc(size_t sz) {
void *t;

t = malloc(sz);

if ((!t) && (!sz))
t = malloc(1);

if (!t) exit(EXIT_FAILURE);

return t;
}

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov
--
Posted via a free Usenet account from http://www.teranews.com

Jun 19 '07 #30

P: n/a
Stephen Sprunk wrote:
"Eric Sosman" <Er*********@sun.comwrote in message
news:1182292165.934849@news1nwk...
>CBFalconer wrote On 06/19/07 17:36,:
>> if (!(t = malloc(sz))) exit(EXIT_FAILURE);
....
>>Very complex. Will never return NULL.

if (!(t = malloc(sz)) && sz 0) ...

That cure is almost as bad as the cause, since it violates the
(informal)documentation given.

#include <stdlib.h>
/* like malloc(), but never returns NULL */
void *xmalloc(size_t sz) {
void *t;

t = malloc(sz);

if ((!t) && (!sz))
t = malloc(1);

if (!t) exit(EXIT_FAILURE);
I'd be tempted to replace or precede this line with

assert( t );

to give some indication as to why the program exits unexpectedly.

--
Ian Collins.
Jun 19 '07 #31

P: n/a
Malcolm McLean wrote, On 19/06/07 22:39:
>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:ur*********************@bt.com...
>Malcolm McLean said:
>>>
"Richard Heathfield" <rj*@see.sig.invalidwrote in message
news:7o******************************@bt.com.. .
Malcolm McLean said:

<snip>

There quite a strong case for a safemalloc() library function that
does terminate with an error message on fail.

No, there isn't. Library routines have no business deciding to
terminate the program.

The problem is that the code is disproprtionate.

If you try hard enough, the code /can/ be disproportionate.
>>Let's say I want to set up a structure with a list of strings.

I looked at your code, and found it lacking in any significant evidence
that you are a regular clc subscriber.

<snip>
>>Now that is about as simple as an arbitrary dataset is likely to be -
just an array of strings. I counted 14 lines purely to handle malloc()
failures.

Get back to me when you've written it properly.
>>The code is untested and there is probably something wrong with it.

You'd be amazed. Still, look on the bright side - it didn't actually
call gets().
>>To my mind this is a very serious disadvantage of the "caller handles
error" paradigm.

To my mind it was just a bunch of broken code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char **str;
int N;
} STRINGS;

STRINGS *makestrings(char *data);
void killstrings(STRINGS *s);

/*
take a comma-separated list of strings, and create
structure with separate strings.
Params: data - the input
Returns: strings object
*/
STRINGS *makestrings(char *data)
{
STRINGS *answer;
char *ptr, *next;
size_t len;
int i;

answer = malloc(sizeof(STRINGS));
if(!answer) /* 1 */
goto error_exit; /* 2 */
answer->str = 0; /* 3 */
This isn't handling a malloc failure, it is is actually completely
pointless the way you have written your code.
answer->N = 1;
for(i=0;data[i];i++)
if(data[i] == ',')
answer->N++;
Having started answer->N at 1 how do you expect it to reach 0 on
incrementing? Overflowing an int invokes undefined behaviour which is
likely to give you a negative value and screw things up earlier. Of
course, if you had used size_t it would wrap and be easy to trap...

Note that this error trapping would be nothing to do with trapping
malloc failures either.
if(!answer->N) /* 4 */
return answer; /* 5 */
answer->str = malloc(answer->N * sizeof(char *));
<snip>

You really should do some vaguely sane formatting if you want people to
read your code. The above formatting suggests you think the above is in
the for loop which clearly it isn't.

I don't know about other people, but I have little patience with badly
formatted code from someone who has been around long enough to know how
to format sanely, so I've not bothered reading the rest..
--
Flash Gordon
Jun 20 '07 #32

P: n/a
Eric Sosman wrote:
CBFalconer wrote On 06/19/07 17:36,:
>Malcolm McLean wrote:

... snip ...
>>>But what if you don't have a program at all because with the 33:67
payload to malloc recovery ratio, it costs too much to write?

Sometimes it's an issue, sometimes not. If you are writing
Microsoft's next OS you have practially infinite resources. If
you're knocking up a game on a tight budget, it is no good missing
Christmas. If it crashes out one every hundred hours of gameplay,
that's not ideal but it isn't the end of the world either. If it is
two months late it might be canned, then you get zero royalties,
and no-one will ever play it.

Are you crippled? Write your own:

#include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);

if (!(t = malloc(sz)) && sz 0) ...
> return t;
}

Very complex. Will never return NULL.
Thanks for the correction. I always forget that.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net
--
Posted via a free Usenet account from http://www.teranews.com

Jun 20 '07 #33

P: n/a
Ian Collins said:
Stephen Sprunk wrote:
<snip>
> void *t;

t = malloc(sz);

if ((!t) && (!sz))
t = malloc(1);

if (!t) exit(EXIT_FAILURE);
I'd be tempted to replace or precede this line with

assert( t );

to give some indication as to why the program exits unexpectedly.
Not in C90 you wouldn't. In C90, you'd be tempted to replace or precede
it with assert(t != NULL);

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #34

P: n/a
CBFalconer said:

<snip>
#include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.
That's a great solution for students, but anyone writing code like that
in the Real World needs to be re-trained or, if necessary, transferred
to Marketing.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #35

P: n/a
Malcolm McLean said:
If it
crashes out one every hundred hours of gameplay, that's not ideal but
it isn't the end of the world either.
True, but it may well be the last game from that company that my kids
ever buy.
If it is two months late it
might be canned, then you get zero royalties, and no-one will ever
play it.
No-one wants to play games written by incompetent programmers, either.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #36

P: n/a
Flash Gordon said:

<snip>
I don't know about other people, but I have little patience with badly
formatted code from someone who has been around long enough to know
how to format sanely, so I've not bothered reading the rest..
I took a brief look, but I felt that *either* Malcolm was trying to
write bad code (in which case he was being disingenuous at best) or he
was trying to write good code (in which case I pity his customers).

Hanlon's Razor suggests the latter.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #37

P: n/a
"Malcolm McLean" <re*******@btinternet.comwrote:
"Richard Bos" <rl*@hoekstra-uitgeverij.nlwrote in message
news:46***************@news.xs4all.nl...
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
In article <R8*********************@bt.com>,
Malcolm McLean <re*******@btinternet.comwrote:

The Turing machine has run out of tape. That's a different kind of
problem
to the others you have described.

Of course it's a different kind of problem: it would mean that you've
reached the end of infinity, probably having forgotten to save some
Scotch to find out whether infinite aging makes Scotch infinitely better.
No. It's asymptotic, but to an asymptote that varies with the brand and
variety.
My sister has a wonderful saying.

Why value smoothness? Why not value fire?
Feel free to send your sister over to me, and I'll set fire to her leg
hairs.

Richard
Jun 20 '07 #38

P: n/a
Richard Heathfield wrote:
CBFalconer said:

<snip>
> #include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.

That's a great solution for students, but anyone writing code like
that in the Real World needs to be re-trained or, if necessary,
transferred to Marketing.
And what do you object to? Kindly elide 'missing braces' and the
possibility of sz == 0.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline dot net

--
Posted via a free Usenet account from http://www.teranews.com

Jun 20 '07 #39

P: n/a
In article <Da*********************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:
>CBFalconer said:

<snip>
> #include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.

That's a great solution for students, but anyone writing code like that
in the Real World needs to be re-trained or, if necessary, transferred
to Marketing.
From the OpenSSH 4.6 source code:
--------
void *
xmalloc(size_t size)
{
void *ptr;

if (size == 0)
fatal("xmalloc: zero size");
ptr = malloc(size);
if (ptr == NULL)
fatal("xmalloc: out of memory (allocating %lu bytes)", (u_long) size);
return ptr;
}
--------
fatal() writes an error message and terminates; this is the only place in
any of the OpenSSH tools (except ssh-keyscan, which isn't typically used
other than for configuration purposes) where malloc is called directly,
and everything else goes through here. Similar wrappers exist for every
other function that dynamically allocates memory.

I wouldn't exactly call SSH "not real world". I think you'd have trouble
arguing that the people who wrote this code didn't carefully consider
what was and wasn't appropriate behavior on memory allocation failure
before they wrote it this way, even if you disagree with their conclusion.
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
[A]s Mark Twain was supposed to have said, "History doesn't repeat itself, but
it does rhyme." (This does not appear to be an actual Twain quote. There is
also a version with "it echos".) --Chris Torek in comp.lang.c
Jun 20 '07 #40

P: n/a
CBFalconer said:
Richard Heathfield wrote:
>CBFalconer said:

<snip>
>> #include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.

That's a great solution for students, but anyone writing code like
that in the Real World needs to be re-trained or, if necessary,
transferred to Marketing.

And what do you object to?
The exit() call.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #41

P: n/a
Dave Vandervies said:
Richard Heathfield wrote:
<snip>
>>That's a great solution for students, but anyone writing code like
that in the Real World needs to be re-trained or, if necessary,
transferred to Marketing.

From the OpenSSH 4.6 source code:
--------
void *
xmalloc(size_t size)
{
void *ptr;

if (size == 0)
fatal("xmalloc: zero size");
ptr = malloc(size);
if (ptr == NULL)
fatal("xmalloc: out of memory (allocating %lu bytes)",
(u_long) size);
return ptr;
}
Send them all to Marketing!

<snip>
I wouldn't exactly call SSH "not real world". I think you'd have
trouble arguing that the people who wrote this code didn't carefully
consider what was and wasn't appropriate behavior on memory allocation
failure before they wrote it this way, even if you disagree with their
conclusion.
Well, since I wasn't in on their discussion I obviously can't argue that
they did, or that they did not, carefully consider any of the above.
What I can argue is that a library function has no business taking the
decision of whether to continue or to terminate out of the hands of the
application programmer. Since xmalloc does take that decision out of
the hands of the programmer, I wouldn't want it in any program I ever
wrote. Student programming, through and through.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #42

P: n/a
In article <46***************@yahoo.com>,
CBFalconer <cb********@maineline.netwrote:
>Richard Heathfield wrote:
>> if (!(t = malloc(sz))) exit(EXIT_FAILURE);
>That's a great solution for students, but anyone writing code like
that in the Real World needs to be re-trained or, if necessary,
transferred to Marketing.
>And what do you object to?
Exiting without an error message is very unhelpful. If there's no
practical way to recover from the error, you should at least say what
the error is.

I'd also recommend saying how many bytes you were trying to allocate:
I've more than once seen messages along the lines of "failed to
allocate 4294967295 bytes" which immediately pointed to bugs in the
code.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jun 20 '07 #43

P: n/a
In article <tp******************************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:
>What I can argue is that a library function has no business taking the
decision of whether to continue or to terminate out of the hands of the
application programmer. Since xmalloc does take that decision out of
the hands of the programmer, I wouldn't want it in any program I ever
wrote.
Provided it documents what it does, you have the decision of whether
to call it or not. Frequently the purpose of a function called
"xmalloc" is to provide the application programmer with a quick way to
"malloc() or quit".

Or perhaps you're arguing that the decision has been taken out of the
hands of programmers who call functions that call xmalloc(), assuming
that those functions are intended to be used as a library. Ideally
they would return an error status, but often it would be a great
overhead to be able to clean up enough to continue after a malloc()
failure. Whether it's worth the effort is just one of those tradeoffs
you make all the time - do we expect users to need to recover? will
enough of them need it to justify the work? will writing the program
become so boring that I won't bother writing it if I have to do that?

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jun 20 '07 #44

P: n/a
Richard Tobin said:

<snip>
Or perhaps you're arguing that the decision has been taken out of the
hands of programmers who call functions that call xmalloc(), assuming
that those functions are intended to be used as a library.
Yes.
Ideally
they would return an error status, but often it would be a great
overhead to be able to clean up enough to continue after a malloc()
failure. Whether it's worth the effort is just one of those tradeoffs
you make all the time - do we expect users to need to recover? will
enough of them need it to justify the work? will writing the program
become so boring that I won't bother writing it if I have to do that?
Suits me. I'll write it instead, once the cheque clears.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #45

P: n/a
Richard Tobin wrote On 06/20/07 12:54,:
In article <tp******************************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:

>>What I can argue is that a library function has no business taking the
decision of whether to continue or to terminate out of the hands of the
application programmer. Since xmalloc does take that decision out of
the hands of the programmer, I wouldn't want it in any program I ever
wrote.


Provided it documents what it does, you have the decision of whether
to call it or not. Frequently the purpose of a function called
"xmalloc" is to provide the application programmer with a quick way to
"malloc() or quit".

Or perhaps you're arguing that the decision has been taken out of the
hands of programmers who call functions that call xmalloc(), assuming
that those functions are intended to be used as a library. Ideally
they would return an error status, but often it would be a great
overhead to be able to clean up enough to continue after a malloc()
failure. Whether it's worth the effort is just one of those tradeoffs
you make all the time - do we expect users to need to recover? will
enough of them need it to justify the work? will writing the program
become so boring that I won't bother writing it if I have to do that?
These are questions that can only be answered in the
context of a particular program, not in that of a general-
purpose library. I myself quite often use a malloc-or-quit
wrapper, but I only call it from program-specific functions
and never from library routines written for reusability.
If my skip list can't allocate memory it returns a failure
code; it doesn't yank the rug out from under the rest of
the program. On the other hand, my "initialize the data
structures that are specific to this program, without which
the program has no hope of running" function quite happily
calls malloc-or-die. Or fopen-or-die, or even parse-input-
line-or-die-on-syntax-error.

Program-level decisions are feasible because their scope
is known: You know what the program's purposes and context
are. Library-level decisions are made *without* knowledge
of scope, and hence should follow the "first, do no harm"
rule.

--
Er*********@sun.com
Jun 20 '07 #46

P: n/a

"CBFalconer" <cb********@yahoo.comha scritto nel messaggio news:46***************@yahoo.com...
Richard Heathfield wrote:
>CBFalconer said:

<snip>
>> #include <stdlib.h>
void *xmalloc(size_t sz) {
void *t;

if (!(t = malloc(sz))) exit(EXIT_FAILURE);
return t;
}

Very complex. Will never return NULL.

That's a great solution for students, but anyone writing code like
that in the Real World needs to be re-trained or, if necessary,
transferred to Marketing.

And what do you object to? Kindly elide 'missing braces' and the
possibility of sz == 0.
Quitting the program without giving anybody a clue of why?
Jun 20 '07 #47

P: n/a

"Richard Tobin" <ri*****@cogsci.ed.ac.ukha scritto nel messaggio news:f5***********@pc-news.cogsci.ed.ac.uk...
In article <tp******************************@bt.com>,
to call it or not. Frequently the purpose of a function called
"xmalloc" is to provide the application programmer with a quick way to
"malloc() or quit".
#include <iso646.h>
#include <stdlib.h>
#define quit exit(EXIT_FAILURE)
/*

....whoops, both operands of || must have scalar type...
*/
#undef quit
#define quit (exit(EXIT_FAILURE), 0)

....
(p = malloc(200)) or quit; /* ;-) */
Jun 20 '07 #48

P: n/a
Richard Heathfield <rj*@see.sig.invalidwrote:
Malcolm McLean said:
If it is two months late it
might be canned, then you get zero royalties, and no-one will ever
play it.
No-one wants to play games written by incompetent programmers, either.
Quite so, but the fact that no one wants to run an OS written by
incompetent programmers unfortunately does not remove the necessity of
doing so. If the choice is between releasing a game with bugs (which
may or may not be fixed) and not releasing the game, the choice for
most game developers is clear.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jun 20 '07 #49

P: n/a
Christopher Benson-Manica said:
Richard Heathfield <rj*@see.sig.invalidwrote:
>Malcolm McLean said:
If it is two months late it
might be canned, then you get zero royalties, and no-one will ever
play it.
>No-one wants to play games written by incompetent programmers,
either.

Quite so, but the fact that no one wants to run an OS written by
incompetent programmers unfortunately does not remove the necessity of
doing so. If the choice is between releasing a game with bugs (which
may or may not be fixed) and not releasing the game, the choice for
most game developers is clear.
Oh, the choice they /do/ make is clear, yes. And the choice they
/should/ make is clear, too. And they are not the same.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jun 20 '07 #50

94 Replies

This discussion thread is closed

Replies have been disabled for this discussion.