When to check the return value of malloc

E

Eric Sosman

I think you have a serious misunderstanding here. realloc does not always
call free, for example if it is passed a smaller size to reallocate. It
is nice to be able to pass NULL to realloc to get extra functionality,
with free there is no new functionality from passing NULL.

realloc() need not actually call free(), of course. However,
it must occasionally do the same thing free() does: De-allocate a
formerly-allocated region and make it available for re-allocation.
I've shown a scenario in which it is convenient for realloc() to
operate with a NULL first argument (that is, "de-allocate" the
non-existent old region). Since it's doing "the same thing" as
free(), things are more consistent if we can say "When realloc()
cannot readjust the old region in place, it allocates a new region,
copies the relevant data, and treats the old region `as if by' free()."

Also, some realloc() implementations will *always* move the region,
even when shrinking it or when there happens to be a "gap" right after
it. And then they'll fill the old region with 0xDEADBEEF or some such.
Can you guess why a realloc() implementor would choose to do this?
I don't see why at all.


You may not have used many implementations then. Maybe the division is
getting optimized out - try volatile. For example on gcc

main()
{
volatile a=0;
a=1/a;
}

Running this on Linux produces,
Floating point exception

"He sees, but he does not observe." -- S. Holmes

Ponder this, Sandeep: How did the computer know it should emit
a "Floating point exception" message? What prompted it do do so?
Is this just something computers do every now and again, when the
whim strikes them?[*] Funny coincidence that the whim happened to
strike just at the moment when a zero division was attempted,
don't you think?

Or, hey, wait: Maybe a check was made? Naaah, too obvious ...

[*] Sometimes it seems that way, doesn't it? But somehow there
always turns out to be some other excuse for their whimsical behavior.
Computers are liberally endowed with what my grandfather called "the
innate animosity of inanimate objects," but you'll never get them to
actually admit how much they enjoy messing with our minds.
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.

What would you think of passing a null pointer to fflush()?
Or to system()? Or to tmpnam(), or as the second argument to
setlocale(), or as the first argument to strtok(), or as the
first argument to freopen(), or as an operand of ==, or ...?

All of these functions have well-defined behaviors when the
argument/operand is a null pointer. So does free().
 
K

Keith Thompson

Kenneth Brody said:
sandeep said:
Seebs writes: [... Passing NUL to free() ...]
It doesn't matter how easy or hard it is for the implementor to comply.
They are *REQUIRED* to correctly do nothing without crashing if a null
pointer is passed to free(). As it happens, this is very easy.

You may get away with it,

No, the language standard *requires* that you can get away with it.
There's no "may" about it.
but passing a NULL pointer to free is a mark of careless code, it
should never happen.

There, you have half a point. IIRC it's the first point you've made that
might reasonably be defended.

Consider:

* Any value returned my malloc() must be able to be passed to free().
* malloc() can return NULL.

The first is an assumption, and I can't think of any strong
justification for it. Standard C happens to satisfy that assumption,
but it didn't need to.
So, unless you were to write the standard to say, in effect, "you can
only pass NULL to free() if malloc() has previously returned NULL".
And then you have to take into account the case of multiple NULL
returns from malloc().

Not at all. The standard could easily have been written to say
that free(NULL) invokes undefined behavior.
After all, the following must be legal:

char *foo = malloc(1000000); /* Returns NULL in our example */
char *bar = malloc(1000000); /* Also returns NULL */
free(foo);
free(bar);

Why? I mean, it certainly is in standard C, but why *must* it be?
Consider the ramifications of not explicitly allowing free(NULL).

The ramification is simply that you'd have to write:

char *foo = malloc(1000000);
char *bar = malloc(1000000);
if (foo != NULL) free(foo);
if (bar != NULL) free(bar);

or equivalent.

Consider, for example, that fopen() may return a null pointer, but
fclose(NULL) invokes undefined behavior. This is an inconsistency
in the language, but not a horrible one.

The real point, of course, is that *given* the fact that the C
standard guarantees that free(NULL) is harmless, and that there
are almost certainly no remaining C implementations in common use
where free(NULL) does anything bad, there's no good reason to go
out of your way to avoid calling free() with a null pointer argument.

On the other hand, if you need to test it anyway for some other
reason, you might as well make the free() call conditional on the
result of the test; there's no point in free()ing a pointer that
you *know* is null.
 
S

Seebs

I think you have a serious misunderstanding here.

You are, as usual, wrong about this.
realloc does not always
call free,

No one asserted that it did. However, there is no more reason for free(NULL)
to be a problem than for realloc(NULL, size) to be a problem.
for example if it is passed a smaller size to reallocate. It
is nice to be able to pass NULL to realloc to get extra functionality,
with free there is no new functionality from passing NULL.

In neither case does it give "new functionality". What it gives you is
the ability to use a null pointer to represent a zero-size/unused allocation,
and "free" it so the code path is simpler.
You may not have used many implementations then. Maybe the division is
getting optimized out - try volatile. For example on gcc

main()
{
volatile a=0;
a=1/a;
}

Running this on Linux produces,
Floating point exception

That sounds like it's checking! :)
What would you think of passing a NULL pointer to strlen or fclose?

That would be undefined behavior.
Even
if you can get away with it in the case of free, it is sloppy programming.

No, it isn't. It's a supported, standard, feature, and there's no reason
not to use it. There's no particular reason to check for null pointers
before calling a function which has well-defined behavior with null pointers.

Consider:

/* error out, printing a message if one is provided */
void
err(char *s) {
fprintf(stderr, "an error occurred");
if (s) {
fprintf(stderr, ": %s\n", s);
}
fprintf(stderr, "\n");
exit(1);
}

Do you consider it "sloppy programming" to call this function with a
null pointer? It's *designed* to accept a null pointer. It is safe,
reliable, and clearly documented as to what it will do.

How about:
x = time(NULL);

It seems to me that you have one of the most dangerous flaws a novice
programmer can have -- you're too proud to admit mistakes. You made the
claim that it was unsafe to call free(NULL). You were wrong. Rather than
admit that you were wrong, you argued about reasons for which you thought
it was actually unsafe, going so far as to claim that the *language
definition* was incorrect and overlooked important things about how free()
was implemented.

And now, rather than admit that you were completely wrong, you're explaining
that it's "sloppy" of people to use a language feature as intended, and
arguing with people at length about it.

Start by admitting that you were wrong, and that you did not understand
the significance of something being the language definition, and if you want
to argue that it's bad style to call free() with a null pointer, it'll be an
interesting discussion. I disagree with your position, but it is legitimately
a matter of opinion. But as long as you seem to be using that style point
solely as a way to avoid admitting that you said things that were simply,
flatly, untrue, you're going to have a credibility gap.

You have to stop minding that sometimes you're wrong. It's great to try to
improve and to stop making mistakes. It's a bad thing to be unwilling to
admit that you made mistakes. Trust me! I am an *expert* in making
stupid mistakes when posting to Usenet!

-s
 
D

Dennis \(Icarus\)

Phil Carmody said:
One might say my understanding has been almost preternatural.
I correctly worked out what language he was using, a language
to which this newsgroup is not dedicated, despite the fact
that he never explicitly stated it.

I didn't think it really needed to be mentioned, as it was not particularly
germane to the point I was making, as regards micro-optimizations.
Being more concerned about something like function call overhead, when
reworking one's algorithms can have much greater impact.
That's a concern independent of language.

Dennis
 
K

Keith Thompson

Richard Heathfield said:
Nisse Engström wrote: [...]
I don't recall reading anything
about the hand-brake and Stop signs in the Highway Code,

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.

Do British cars have lousy brake pedals?

When I stop at a stop sign or a red light, I just press down on the
brake pedal firmly enough to keep the car from moving. No particular
guessing or finesse is required, even on a slope; it's not difficult
to apply sustantially more pressure than is required to stop the car.
 
D

Dann Corbit

Richard Heathfield said:
Nisse Engström wrote: [...]
I don't recall reading anything
about the hand-brake and Stop signs in the Highway Code,

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.

Do British cars have lousy brake pedals?

When I stop at a stop sign or a red light, I just press down on the
brake pedal firmly enough to keep the car from moving. No particular
guessing or finesse is required, even on a slope; it's not difficult
to apply sustantially more pressure than is required to stop the car.
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.

We could be even safer by putting the transmission into park and turning
off the engine.

Then we can get out and chock the wheels.

;-)
 
P

Phil Carmody

Dennis \(Icarus\) said:
I didn't think it really needed to be mentioned, as it was not particularly
germane to the point I was making, as regards micro-optimizations.
Being more concerned about something like function call overhead, when
reworking one's algorithms can have much greater impact.
That's a concern independent of language.

If you consider the problem of arbitrarily-complicated functions
being automagically called when there's no explicit function call
in the code and where such processing may be undesirable to be
one of merely a 'function call overhead', then you have been
indoctrinated way too much.

Phil
 
I

Ian Collins

Keith Thompson ha scritto:

i dont know if in italy there is such a requirement to use the
handbrake, but my instructor taught me to stop at an upward sloping
crossing with footbrake *and* then to stay in position waiting for the
moment to move again using neither brakes, but simply using the minimum
force from the engine to avoid rolling down backawds :)

Now you know why the Brits joke about Italian drivers!
 
R

robertwessel2

Richard Heathfield said:
Nisse Engström wrote: [...]
I don't recall reading anything
about the hand-brake and Stop signs in the Highway Code,
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.

Do British cars have lousy brake pedals?

When I stop at a stop sign or a red light, I just press down on the
brake pedal firmly enough to keep the car from moving.  No particular
guessing or finesse is required, even on a slope; it's not difficult
to apply sustantially more pressure than is required to stop the car.


No, they just have vastly more cars with manual transmissions (in the
US manual transmissions account for about 8-9% of vehicle sales - the
majority going into sports cars and ultra low end cars, in Europe,
OTOH, something like 75% of cars sold have manual transmissions). Nor
is using the handbrake for a stop on an incline really taught in the
US, except (occasionally) as a beginner technique for a standard
transmission, although I suspect in places like San Francisco it's
rather more popular.

Or you could just learn to heel-and-toe. ;-)
 
N

Nick Keighley

io_x wrote:

go Forth and, er Forth
That's an interesting perspective, but not one that would keep you
employed for very long. Other than as an interesting intellectual
exercise (or, perhaps, as an IOCCC entry), a program that is optimised
for source code length is of no use whatsoever. Programs should be
readable, and readability *requires* redundancy.

isn't this the guy that used to post programs full of syntax
compressing macros?

#define I if
#define F for
#define M main
#define P printf
#define X exit (0)

M () {P("hello"); X;}

Not if it is at the expense (and I do mean *expense*) of a reduction in
readability.

so no APL then?
 
W

Willem

superpollo wrote:
) i dont know if in italy there is such a requirement to use the
) handbrake, but my instructor taught me to stop at an upward sloping
) crossing with footbrake *and* then to stay in position waiting for the
) moment to move again using neither brakes, but simply using the minimum
) force from the engine to avoid rolling down backawds :)

With a manual transmission ? The mind boggles. Although I've seen
people do that in .nl as well; constantly rolling up and down trying
to stay in the same place, very annoying to look at.

How often do you have to replace the clutch plates in Italian cars ?


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 
N

Nick Keighley

There, you have half a point. IIRC it's the first point you've made that
might reasonably be defended.

#include <stdlib.h>

typedef struct
{
int id;
double param;
int busy;
} Equip;

Equip* allocate_stuff (int n)
{
int i;
Equip **array;

if ((array = malloc(n * sizeof(Equip*))) == NULL)
goto cleanup;

for (i = 0; i < n; i++)
if ((array = malloc(sizeof(Equip))) == NULL)
goto cleanup;

return *array;

cleanup:
for (i = 0; i < n; i++)
free (array);

free (array);
return NULL;
}

int main (void)
{
Equip *equip_list = allocate_stuff (100);
return equip_list ? 0 : 1;
}

[for extra points: how many deviations from the clc programming
standards are there in that code?]
 
R

Richard Bos

sandeep said:
You may get away with it, but passing a NULL pointer to free is a mark of
careless code, it should never happen.

Either you _are_ a troll, or you are simply ignorant about real C. In
either case, stop trying to tell your elders and betters how to suck
hard-boiled eggs.

Richard
 
R

Richard Bos

Keith Thompson said:
The first is an assumption, and I can't think of any strong
justification for it. Standard C happens to satisfy that assumption,
but it didn't need to.

It is more elegant, and allows for more elegant code. Granted, it's not
a _compelling_ argument, but IMAO it's strong enough.
Consider, for example, that fopen() may return a null pointer, but
fclose(NULL) invokes undefined behavior. This is an inconsistency
in the language, but not a horrible one.

And, indeed, it would have been more elegant if fclose(NULL) did
nothing. Presumably the reason why the Standard doesn't require this is
"existing implementations did not", but it would have been more elegant.

Richard
 
B

Ben Bacarisse

Equip* allocate_stuff (int n)
{
int i;
Equip **array;

if ((array = malloc(n * sizeof(Equip*))) == NULL)
goto cleanup;

for (i = 0; i < n; i++)
if ((array = malloc(sizeof(Equip))) == NULL)
goto cleanup;

return *array;

cleanup:
for (i = 0; i < n; i++)
free (array);

free (array);
return NULL;
}

[for extra points: how many deviations from the clc programming
standards are there in that code?]

Hmm... no idea, but it's undefined behaviour (in cleanup, array is UB
when array == NULL and array[x] is UB for all x > i at the same point).

I do get your point (that it's easier just to free all the second-level
pointers) but an obvious alternative presents itself: i tells you how
many valid pointers there are. Just don't re-use it for the free loop.

Aside: this is one reason I like C99's 'for (int x = 0; ...)'. If used
consistently it can tell you more about the purpose of counters. The
first malloc loop would not use it, thereby indicating that it's counter
is used later.
 
N

Nisse Engström

When I stop at a stop sign or a red light, I just press down on the
brake pedal firmly enough to keep the car from moving. No particular
guessing or finesse is required, even on a slope; it's not difficult
to apply sustantially more pressure than is required to stop the car.

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.


/Nisse
 
N

Nisse Engström

With a manual transmission ? The mind boggles. Although I've seen
people do that in .nl as well; constantly rolling up and down trying
to stay in the same place, very annoying to look at.

How often do you have to replace the clutch plates in Italian cars ?

When I did my round of national service, my driving
instructor taught me how to shift gears without using
the clutch, but that only worked on their oldest
vehicles. :)


/Nisse
 
J

James Kuyper

Richard said:
In the UK, driving instructors frown on this practice, because you're
not ready to move off (i.e. right foot poised over accelerator).

Odd - that's precisely the reason why fully depressing the pedal was
favored by my driving instructors. By forcing you to take the time to
switch pedals, it avoids "jack-rabbit" starts, which can be dangerous if
some idiot runs the red light across your path right after your own
light turns green.
... This
would count, in the UK at least, as "inconsiderate driving", ...

Again, odd - "jack-rabbit" starts are considered "inconsiderate driving"
in this country - which is not meant to imply that they're rare.
... especially
if you're on a slight upward slope (so that the car starts to roll
backwards when you remove your foot from the brake to move it over to
the accelerator).

That doesn't happen with the automatic transmission vehicles I've used;
they always apply sufficient torque to prevent rolling backwards, even
before you hit the gas pedal. My own car has a manual transmission, and
learning how to avoid that backward roll was one of the most
ridiculously difficult things I had to learn during my first month or so
of using a manual transmission. However, it's now something I do so
automatically, I can't even explain how I do it - but it's not hard at
all to do except on the very steepest slopes. Slopes that steep are
quite rare in most of the areas I've driven (Los Angeles, and the
Washington DC metropolitan area).
 
E

Ersek, Laszlo

superpollo ha scritto:

The clutch friction disc industry must flourish in Italy.

the point being, that doing so you can move off quickier when the time
comes.

So this is what the expression "jack-rabbit start" means.

I knew driving styles differ from country to country, but I didn't imagine
local style would be ingrained in the driving curriculum this deeply.

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

Cheers,
lacos
 
T

Tim Streater

"Ersek said:
The clutch friction disc industry must flourish in Italy.



So this is what the expression "jack-rabbit start" means.

I knew driving styles differ from country to country, but I didn't imagine
local style would be ingrained in the driving curriculum this deeply.

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

Oh sure. That must be why I stepped out of a hotel in a German city a
few years ago, and watched a woman do a U-turn and smash straight into a
car coming the other way. I saw two other accidents during the total of
three days I was there.
 

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

No members online now.

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top