When to check the return value of malloc

T

Tim Streater

Nisse Engstrom said:
That's what we do, clutch and foot-break. Unless, of course,
you're stopping on a slope, but that's got nothing to do
with stop signs. We have plenty of stop signs in Sweden. In
particularly difficult or accident-prone locations, you may
even find junctions with stop signs in all directions.

By and large stop signs are unnecessary, which is why we have so few of
them in the UK, and a very low accident rate. Road signs in the US
appeared to be intended to raise revenue, far as I could tell.
 
N

Nisse Engström

4. Don't use "uLL" on a constant that's unambiguously within the size
range of an ordinary signed long. You don't need any qualifier at all,
although in theory a system could exist where that value is too big for
size_t, in which case you'd be allocating 0 bytes.

The "uLL" suffix ensures that any integer arithmetic
performed on ESIZE is done using an unsigned type
(unless there are wider types). Without the suffix,
you may end up using signed arithmetic which might
cause unnecessary overflows.


/Nisse
 
S

Seebs

The "uLL" suffix ensures that any integer arithmetic
performed on ESIZE is done using an unsigned type
(unless there are wider types). Without the suffix,
you may end up using signed arithmetic which might
cause unnecessary overflows.

If any arithmetic were ever to be performed on the value, this might
be a significant consideration. However, the key point I was making was
not about the U, which is reasonable, but about the LL, which is not.

-s
 
R

Richard Bos

Phil Carmody said:
Do you think I'm the kind of idiot who would waste time doing that?

Why would _we_ be the kind of idiots who would waste time trying to
figure out what you mean when you speak in riddles - for the thatmuchth
time? Speak your mind, and speak it clearly, if you want to be
understood.

Richard
 
R

Richard Bos

Ersek said:
(Personally I think Germans have the best cars, the best roads, and the
best driving style.)

Hah! When I'm being tailgated, in 99% of the cases, it's either a German
make or a German plate.

Richard
 
J

Joachim Schmitz

Richard said:
Hah! When I'm being tailgated, in 99% of the cases, it's either a
German make or a German plate.

You know what happens if a Dutch fails driving test the 3rd time? He gets
the license, but has to drive a car with a yellow number plate... ;-)

Bye, Jojo
 
S

Seebs

You know what happens if a Dutch fails driving test the 3rd time? He gets
the license, but has to drive a car with a yellow number plate... ;-)

Driving tests scare me. Around here, you need a score of 70% to pass.
In theory, that ought to imply that, at any given time, there is a 30%
chance that any driver you see is about to swerve unexpectedly into you.

While in fact it doesn't quite work out that way, it pays off to be about
that cautious about other drivers.

.... Dragging this on topic: The same mostly goes for code. I find it very
rewarding to write code as though the people reading my code are likely to
be fairly inexperienced and a little careless. If nothing else, this saves
a lot of time if I have to work on the code later, because I am nearly
always a little careless. I have found extremes I'm not willing to go
to (I'm not going to try to accommodate people who don't know that C
statements end with semicolons, or who don't know what "extern" means),
but in general, as I get more experienced and better, I tend to write
more and more simply and clearly.

I gotta track down a thing I found recently, an actual roguelike game I
wrote in college, which is atrocious. Up to and including "void main".

-s
 
J

James Harris

Yes (except for the physical description, which I got hopelessly wrong),
unless you are an exceptionally fine driver.

 > I don't recall reading anything


Well, the Highway Code is not a full definition of the law, but it does
say "You MUST stop behind the line at a junction with a ‘Stop’ sign and
a solid white line across the road" (para171). If you do not apply your
handbrake, you are basing your claim to having "stopped" on your ability
to hold the vehicle exactly on the biting point. Most people can't even
turn right properly, let alone keep a vehicle stationary on even a
fairly gentle slope - so any driving instructor worth his salt will beat
you about the head with a gearstick until you learn to apply the
handbrake at Stop signs *every time*. With the handbrake applied, you
know you've stopped. Otherwise, you're just guessing.

Oh, by the way - if you *don't* apply your handbrake at a Stop sign on
your UK driving test, that's an automatic fail.

I don't agree with much of your post about UK expectations but the
last assertion is the worst! :-( Can you substantiate that last
(outrageous) statement?

James
 
E

Eric Sosman

"Eric Sosman" ha scritto nel messaggio
....

is it because someone in a debugger can see the memory is not free?
(it seems useful because if free() not release the memory to the OS
that memory here not seg-fault if read or write, even if it should be not used)

You're the "terseness is readability" guy, right?

thatsthegeneralideayesthegoalistoexposeanydanglingpointersthat
mightstillbepointingtothememoryasitwasbeforereallocbymovingthe
blockunconditionallyreallocinvalidatesthestalepointerseverytime
andbywipingoutwhateverformerlyinhabitedtheoldblockreallocmakes
itmorelikelythatastalepointeraccessingthatdatawillcausevisible
troublehopethisisterseenoughforyou
 
T

Tim Harig

And when ?: is properly embedded in an expression:

f( p+(a?b:c)+q*(d?e:g))

then I'd really like to see your version using if/else.

Ignoring the visual clues provided by the indentation that there is a
divergence of execution control, your complex statment, while contrived,
doesn't explain why you are doing what you are doing. Why is it that you
might need to total what amounts to different values under *four* different
circumstances?

/* explanation 1 */
if (descriptive_condition_1)
descriptive_name_1 = descriptive_name_2;
else
descriptive_name_1 = descriptive_name_3;

/* explanation 2 */
if (descriptive_condtion_2)
descriptive_name_4 = descriptive_name_5;
else
descriptive_name_4 = descriptive_name_6;

/* explaination 3 */
descriptive_name_7 = descriptive_name2 * descriptive_name_8
vert_object(descriptive_name_9 + descriptive_name_1 + descriptive_name_7);

Notice how much more room there is for comments. Each operation is
logically split into smaller units that can be individually commented
and understood before preceding. Furthermore, the additional and constructive
use of variable names provides even more information about the values that
we are using. This approaches self documentation.

You are so impressed that you saved a little bit of typing; but, what
happens down the road when we find that there are three numbers that could
be associated with x or that if a, we really need to do three things to
know that x should be? Then you have rearange all of this section of
code (not to mention the comments) to accomadate the changes instead of
just adding additional steps to the single unit that is functionally
affected by the change.
 
T

Tim Harig

Why? If the thing that makes the line unreadable is the
fact that it's *embedded in an expression*, then the solution
is to simply *not embed it in an expression*.

int base_foo = a?b:c; /* or ``a ? b : c'' if you like airy code */
int scaled_foo = d?e:g;
f(p + base_foo + q*scaled_foo);

Then what have you gained over just using if/else? A couple of lines in a
source code file? A couple hours pay finding a bug because somebody
overlooked the conditional as a simple statement, while quickly scanning
the code?
There's nothing intrinsically less readable about the ternary ? :
operator than multiple assignments in an if/else.

Intrinsically, maybe not. Practically, the difference can be rather
profound. The simple fact of the matter is that people are much more used
to seeing if/else syntax then ?: and they have become better at visually
processing it. if/else can do things that cannot be legibly done with ?:
so why require somebody reading your code to read two different types of
constructs when one will handle them both.
 
N

Nick Keighley

I do find the airy code easier on the eye
Then what have you gained over just using if/else?  
elegance?


A couple of lines in a
source code file?  A couple hours pay finding a bug because somebody
overlooked the conditional as a simple statement, while quickly scanning
the code?

you might as well argue that { and } and we should all code in Pascal
(actually I /do/ think we should all code in pascal, but that's
another issue :) )

Intrinsically, maybe not.  Practically, the difference can be rather
profound.  The simple fact of the matter is that people are much more used
to seeing if/else syntax then ?:

rather depends on the code base doesn't it?

and they have become better at visually processing it.

do you have figures from cognitive scientists and psychologists?

 if/else can do things that cannot be legibly done with ?:

and vice versa. They are different constructs
so why require somebody reading your code to read two different types of
constructs when one will handle them both.

not really. I was always a fan of Algol-60s (and Coral's)

x := if a = b then 1 else 2;

that is they used the same keywords for both if/elses. Only yesterday
I was arguing with someone who said this was a bad idea and the two
forms /should/ be distinguished.


--

The use of the Chomsky formalism is also responsible for the term
"programming language", because programming languages seemed to
exhibit a strucure similar to spoken languages. We believe that
this term is rather unfortunate on the whole, because a programming
language is not spoken, and therefore is not a language in the true
sense of the word. Formalism or formal notation would have been
more appropriate terms.
Niklaus Wirth
 
P

Phil Carmody

Tim Harig said:
Then what have you gained over just using if/else?

Simpler, more readable code, as there's only one assignment to
each of the intermediate values rather than two.

Simpler, more readable code, as the definition of the intermediate
values is accompanied by the initialisation thereof.
A couple of lines in a
source code file? A couple hours pay finding a bug because somebody
overlooked the conditional as a simple statement

The whole point of the statement is the conditional expression -
anyone who's going to overlook that has no right to be looking
at the code.
, while quickly scanning the code?


Intrinsically, maybe not. Practically, the difference can be rather
profound. The simple fact of the matter is that people are much more used
to seeing if/else syntax then ?: and they have become better at visually
processing it.

Care to cite any scientific studies that back up that claim?
You may get confused by ?:, but I've got a multimegaline codebase
at $DAYJOB which proves that your weakness isn't shared by too
many people.
if/else can do things that cannot be legibly done with ?:
so why require somebody reading your code to read two different types of
constructs when one will handle them both.

Why require someone to match the targets of two separate assignments?
And why require people to separate definition from initialisation?
Goto can do things that cannot legibly be done with if/else,
so why require someone reading your code to read two different
types of control flow when one will handle them both. (Included
ironically purely to show how flawed your logic is.)

Phil
 
N

Nisse Engström

If any arithmetic were ever to be performed on the value, this might
be a significant consideration. However, the key point I was making was
not about the U, which is reasonable, but about the LL, which is not.

I tend to agree. I think I was thinking "unsigned long"
perhaps.


/Nisse
 
B

bart.c

Tim Harig said:
Ignoring the visual clues provided by the indentation that there is a
divergence of execution control, your complex statment, while contrived,
doesn't explain why you are doing what you are doing. Why is it that you
might need to total what amounts to different values under *four*
different
circumstances?

I use this construction all the time, although mostly in a different
language and mostly associated with strings (when there are two or more in
the same expression). An example in C might be:

printf("%d %s in %d
Director%s\n",nfiles,(nfiles=1?"File":"Files"),ndirs,(ndirs=1?"y":"ies"));
Notice how much more room there is for comments.

What comments would be needed in examples such as above?
Each operation is
logically split into smaller units that can be individually commented
and understood before preceding. Furthermore, the additional and
constructive
use of variable names provides even more information about the values that
we are using. This approaches self documentation.
You are so impressed that you saved a little bit of typing; but, what
happens down the road when we find that there are three numbers that could
be associated with x or that if a, we really need to do three things to
know that x should be?

Well in another language I would use: m:=(n|"One","Two","Three"|"Other")...

In C, you might use: m = (n>=1 && n<=3 ? table[n] : "Other");

But, this involves setting up the table[] data, which is a nuisance if it is
only used in this one place. So this is more an argument for extending the
?: feature into a multi-selection operator...

Your solution would presumably be:

switch (n) {
case 1: m="One"; break
case 2: m="Two"; break
case 3: m="Three"; break
default: m="Other";
}

Which would be a major distraction when your code has bigger fish to fry
than just setting a variable to one of 4 values...
 
N

Nisse Engström

with free there is no new functionality from passing NULL.

It allows you to write cleaner code:

p = malloc (...);
q = malloc (...);
r = malloc (...);
s = malloc (...);

if (p && q && r && s) {
/* ok */
} else {
/* error */
}

free (p);
free (q);
free (r);
free (s);

The cleanup would be a lot bulkier (to me) if I had to
add an if() statement before every free().
What would you think of passing a NULL pointer to strlen or fclose? Even
if you can get away with it in the case of free, it is sloppy programming.

I wish fclose(NULL) had the same semantics as free(NULL),
but unfortunately it doesn't. I try to always follow the
free(NULL) pattern when I write code that allocates/frees
some kind of resource. There's nothing sloppy about it.
It's just the cleanest and most obvious way to do it (in
my mind).


/Nisse
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,607
Members
45,240
Latest member
pashute

Latest Threads

Top