473,395 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Can malloc ever really fail?

I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

-Chess
Nov 14 '05 #1
27 4228
Chess Saurus <ch********@yahoo.com> spoke thus:
I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


Why not read a few threads down for a lovely discussion of this very
topic? (Yes, it can fail.)

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #2
In <e7**************************@posting.google.com > ch********@yahoo.com (Chess Saurus) writes:
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
I hope you don't write it like this in your real code! You certainly
don't want to assing 0 or 1 to variable a.
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


Do you have a contract with God (or Satan or whatever) that your
programs will NEVER be executed on a system running out of virtual
memory?

If appropriate to your application, you can do the following:

void *xmalloc(size_t size)
{
void *p = malloc(size);
if (p == NULL) {
/* error code */
exit(EXIT_FAILURE); /* or abort(); */
}
return p;
}

and use xmalloc instead of malloc, without ever checking its return
value.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #3
Chess Saurus <ch********@yahoo.com> wrote:
I'm getting a little bit tired of writing


Then don't use C. Or alternatively some people write an xmalloc() wrapper
which does something like:

void *xmalloc(size_t len) {
void *p = malloc(len);

if (p == NULL)
exit(EXIT_FAILURE);

return p;
}

Of course, don't forget to put a big fat disclaimer on your code/application
which says: Don't under any circumstances depend on this program for
anything other than your own amusement.

Nov 14 '05 #4
ch********@yahoo.com (Chess Saurus) writes:
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}


That doesn't even work. How can you be tired of writing it if
you don't even know how to write it correctly? ;-)
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #5
>I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


The *PROGRAM* can run out of virtual memory well before the *SYSTEM*
runs out of virtual memory. Sometimes particular programs (or
mortal users in general) are limited because having the whole system
come down due to the actions of one memory hog is undesirable.
This feature is sometimes called 'ulimit' (after the shell command
that sets the limits).

One real, practical example: the Exim mail transfer agent tends
(at least it did a couple of years ago when I identified this
problem) to leak a little bit of memory (something around the size
of the message headers, e.g. 2k bytes) each time it rejects a message
for syntax errors in headers. This memory is recovered when the
particular SMTP conversation terminates and the process exits (which
typically happens in less than a minute). Doesn't sound like a big
problem, right, especially for a machine with 500MB of RAM and 1GB
of swap, does it?

Now enter a spammer who establishes a connection ONCE, and sends a
quarter million spams (all rejected, and no, I did not make this
number up, I counted log entries) down that one connection over a
period of a couple of days. Now the process has leaked 500MB, the
system is swapping a lot, and since this isn't the only process
receiving junk from the same spammer, it runs out of swap space,
after having slowed down to a crawl with heavy swapping. In this
case, setting the ulimit low enough to abort the connection after
it had received an unreasonable number of messages prevented this
spammer from killing service for other people actually sending
useful mail. One process would die, the spammer would get dumped
and start up another connection, and continue getting spams rejected.
The rest of the system was relatively unaffected.

Of course, the real fix is to remove the leak, but I didn't know
enough about the internals of the code to do that.

Gordon L. Burditt
Nov 14 '05 #6

"Chess Saurus" <ch********@yahoo.com> wrote in message

I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

It's a theoretical problem much more than a practical problem, on most
systems. No computer can provide infinite memory space. However, as we
discussed elsethread, if you are allocating 100 bytes on a 10MB machine, and
the computer runs out of memory every ten minutes, it will be about two
years before your allocation is the one to get hit, and your error-handling
code executes. Since desktop computers probably break down every two years
or so due to compenent failure, this isn't something to get too worked up
about.

The worst problem is when you use memory internally. Consider this function

/*
check if two points on a maze are connected.
*/
bool connected(const char *maze, int width, int height, int x1, int y1, int
x2, int y2)

The problem is, you will probably write the function using a recurive
floodfill to a temporary buffer, which you have to allocate. So you have to
change the interface to return an out of memory condition, which is messy.
The problem is particularly acute if you design functions top down, and only
realise late on that one function near the bottom needs to allocate some
memory, and then the error has to be propagated up through several
redesigned layers.

Fortunately, most functions which allocate memory will return it, so you can
simply return a NULL pointer to indicate out of memory.

Usually when you are calling malloc() you don't know at compile time how
many bytes you will need, and you always have to be alert for abuse. For
instance a legitimate filename will be under a kilobyte, but a hacker could
pass a name several megabytes long to see if he can exploit the system. So
just ignoring the return isn't a good option.
Nov 14 '05 #7
In article <cd**********@newsg4.svr.pol.co.uk>,
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote:
"Chess Saurus" <ch********@yahoo.com> wrote in message

I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

It's a theoretical problem much more than a practical problem, on most
systems. No computer can provide infinite memory space. However, as we
discussed elsethread, if you are allocating 100 bytes on a 10MB machine, and
the computer runs out of memory every ten minutes, it will be about two
years before your allocation is the one to get hit, and your error-handling
code executes. Since desktop computers probably break down every two years
or so due to compenent failure, this isn't something to get too worked up
about.


If you have a program with 100,000 bugs, which crashes every ten
minutes, it will be about two years before your bug is the one that gets
hit, so there is no point in fixing any bugs, right? Something somewhere
is wrong with that logic...
Nov 14 '05 #8
"Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
"Chess Saurus" <ch********@yahoo.com> wrote in message

I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

It's a theoretical problem much more than a practical problem, on most
systems. No computer can provide infinite memory space. However, as we
discussed elsethread, if you are allocating 100 bytes on a 10MB machine, and
the computer runs out of memory every ten minutes, it will be about two
years before your allocation is the one to get hit, and your error-handling
code executes. Since desktop computers probably break down every two years
or so due to compenent failure, this isn't something to get too worked up
about.


Malcolm's point of view is not universally held. Rather than re-hash
the argument, I refer interested readers to the "If malloc fails"
thread.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9
ch********@yahoo.com (Chess Saurus) wrote in message news:<e7**************************@posting.google. com>...
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


Two solutions come to my mind.

1:

a = malloc(.);
b = malloc(..);
c = malloc(...);
d = malloc(....);
// Don't use either a....d until you perform the test below.
if ( ! ( a && b && c && d ) )
{
// Deal with error;
}
2:
e = malloc( .......... );
if ( ! e ) { /* Deal with error */ }
a[0] = e;
a[1] = e + a_req;
b[0] = a[1] ;
b[1] = b[0] + b_req;
........

Then use a[0] ... d[0] for manipulation.

N.B. The second solution can be improved. Possibly by using
structures. I haven't used it ever. I am just lazy.
--
Imanpreet Singh Arora
isingh AT acm DOT org
Nov 14 '05 #10
"Chess Saurus" <ch********@yahoo.com> wrote in message
news:e7**************************@posting.google.c om...
I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


When I worked at a DotCom that ran Windows webcams online, we would make a
noise whenever someone logged into your webcam and another one when people
left. Popular sites (usually girls online) would trigger the noise many many
times a day.
The problem was that MS had a bug (leak) in their audio routines that
allocated a small chunk of memory everytime you called it. Since the webcam
software ran for days at a time, the 16bits or so added up and caused
programs to fail on the client machine. MS tech support finally admitted it
was their bug, but had no fix other than a periodic reboot.
So, yes, malloc can fail from some other program running a small task in the
background and eating a few bytes at a time.

--
Mabden
Nov 14 '05 #11
On Wed, 21 Jul 2004 11:01:34 -0700, Chess Saurus wrote:
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

Yes.
Not every gadget you program with C uses 'virtual memory'.
You might not even have any memory to use dynamically, as all is used by
the static allocated data, (while code squeezed in some ROMs)
Some sysadmin might limit you to only this'n'that much
memory for your use.
You might turn off swapping entierly.
Not all virtual memory space might be usable, as kernel maps
some, shared libraries might map some.
Your hardware might be faulty.
Your implementation might provide a low hard limit on how much
you can malloc.

Nov 14 '05 #12
"Christian Bau" <ch***********@cbau.freeserve.co.uk> wrote in message

If you have a program with 100,000 bugs, which crashes every ten
minutes, it will be about two years before your bug is the one that gets
hit, so there is no point in fixing any bugs, right? Something somewhere
is wrong with that logic...

Say that you're building car components. There's no point providing a really
super spark plug, guaranteed for fifty years, when the rest of the
components will all start to fail after ten.
Similarly, there's not much point fixing a minor bug, which trips once every
two years, when you have 100,000 bugs causing a failure every ten minutes.
When you've got the failure rate down to once a month or so you can start
looking at the minor problems. Fix the serious bugs first.
If you run MS Windows then you can expect the system to crash once every few
days in general use anyway, so again there's not much practical difference
between 100% error free client software and software which crashes once or
twice a month.
Nov 14 '05 #13
ch********@yahoo.com (Chess Saurus) wrote in message news:<e7**************************@posting.google. com>...
I'm getting a little bit tired of writing

if ((a = malloc(...)) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


Several have responded, but none have provided the correct answers. :-)

One big question is, who are you writing for? If you're writing
long-term industrial-strength software, you surely won't begrudge
a few keystrokes, so I'll assume your application is of limited
and well-defined application, where, as you say, malloc() just ain't
going to fail.

First, my library has a trivial routine mustmalloc() which does the
error test and aborts on failure, so you don't have to code
the error test elsewhere. You lose just four keystrokes ("must")
per invocation. You won't tailor a specific message for each malloc()
failure but who cares? "malloc() won't fail".

Please note that when malloc() *does* fail, you *will* get a descriptive
error message, even without the test. The message usually reads
"Segmentation violation: Core dumped." You know your users better than
I, and will know whether this message is convenient for them, but
the fact that *malloc() doesn't fail* should affect the trade-off.

(I've had only one malloc failure in the last 5-million keystrokes
and that occurred only because I was curious what it would take to
force malloc() to fail. YMMV.)

The reason I'm posting is that you will get several anal-retentive
responses mentioning Murphy's Law.
These messages aren't wrong, but reflect flawed and dogmatic priorities.
For example, responders will ignore that "Malloc failed" usually
isn't much more informative than "Segmentation violation: core dumped"
anyway. (In fact, the latter message may be more useful! It did dump
core, after all.)

There's little harm in a few extra keystrokes, so here the dogmatic
pedants aren't fully wrong.
Get me started though, and I'll tell about some million-dollar software
fiascoes caused by blind adherence to dogma.

James
Nov 14 '05 #14
jd*********@yahoo.com (James Dow Allen) writes:
[...]
Please note that when malloc() *does* fail, you *will* get a descriptive
error message, even without the test. The message usually reads
"Segmentation violation: Core dumped." You know your users better than
I, and will know whether this message is convenient for them, but
the fact that *malloc() doesn't fail* should affect the trade-off.


When malloc() fails, you *will* get undefined behavior if you try to
dereference the returned null pointer. On many (most?) systems, that
undefined behavior will take the form of a segmentation violation or
something similar, but (dogmatic pedant that I am) I don't
particularly want to depend on that.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #15
Keith Thompson wrote:

jd*********@yahoo.com (James Dow Allen) writes:
[...]
Please note that when malloc() *does* fail, you *will* get a descriptive
error message, even without the test. The message usually reads
"Segmentation violation: Core dumped." You know your users better than
I, and will know whether this message is convenient for them, but
the fact that *malloc() doesn't fail* should affect the trade-off.


When malloc() fails, you *will* get undefined behavior if you try to
dereference the returned null pointer. On many (most?) systems, that
undefined behavior will take the form of a segmentation violation or
something similar, but (dogmatic pedant that I am) I don't
particularly want to depend on that.


I've seen systems that allow you to dereference (for reading) a NULL
pointer, and that memory always contained zeros. I don't recall how
many bytes were available at NULL, but enough so that "*(long *)NULL"
would return 0L. (More likely, it would be a case of string operations
acting as if it were a zero-length string.)

Of course, *NULL was write-protected.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody at spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Nov 14 '05 #16
On 21 Jul 2004 18:16:08 -0700, mi************@yahoo.com (Minti) wrote:
ch********@yahoo.com (Chess Saurus) wrote in message news:<e7**************************@posting.google. com>...
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?

Two solutions come to my mind.

1:

a=0; b=0; c=0; d=0; a = malloc(.);
b = malloc(..);
c = malloc(...);
d = malloc(....);
// Don't use either a....d until you perform the test below.
if ( ! ( a && b && c && d ) )
{
// Deal with error; free(a); free(b); free(c); free(d);...
.... }

Nov 14 '05 #17
RoSsIaCrIiLoIA <n@esiste.ee> writes:
On 21 Jul 2004 18:16:08 -0700, mi************@yahoo.com (Minti) wrote:
ch********@yahoo.com (Chess Saurus) wrote in message
news:<e7**************************@posting.google .com>...
I'm getting a little bit tired of writing

if (a = malloc(...) == NULL) {
// error code
}

I mean, is it really possible that a malloc call could fail, except in
the case of running out of virtual memory?


Two solutions come to my mind.

1:

a=0; b=0; c=0; d=0;
a = malloc(.);
b = malloc(..);
c = malloc(...);
d = malloc(....);
// Don't use either a....d until you perform the test below.
if ( ! ( a && b && c && d ) )
{
// Deal with error;

free(a); free(b); free(c); free(d);...
....
}


Initializing a, b, c, and d to 0 before the malloc() assignments is
pointless; they'll be overwritten with whatever malloc() returns.

As for the free()s you've added, that's fairly obviously covered by
"// Deal with error".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #18
On Sat, 24 Jul 2004 02:40:34 GMT, Keith Thompson wrote:
RoSsIaCrIiLoIA <n@esiste.ee> writes:
On 21 Jul 2004 18:16:08 -0700, mi************@yahoo.com (Minti) wrote:
>ch********@yahoo.com (Chess Saurus) wrote in message
>news:<e7**************************@posting.google .com>...
>> I'm getting a little bit tired of writing
>>
>> if (a = malloc(...) == NULL) {
>> // error code
>> }
>>
>> I mean, is it really possible that a malloc call could fail, except in
>> the case of running out of virtual memory?
>>
>
>Two solutions come to my mind.
>
>1:

a=0; b=0; c=0; d=0;
> a = malloc(.);
> b = malloc(..);
> c = malloc(...);
> d = malloc(....);
> // Don't use either a....d until you perform the test below.
> if ( ! ( a && b && c && d ) )
> {
> // Deal with error;

free(a); free(b); free(c); free(d);...
....
> }


Initializing a, b, c, and d to 0 before the malloc() assignments is
pointless; they'll be overwritten with whatever malloc() returns.


Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"
a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }

Nov 14 '05 #19
Kenneth Brody <ke******@spamcop.net> wrote in message news:<41***************@spamcop.net>...
I've seen systems that allow you to dereference (for reading) a NULL
pointer, and that memory always contained zeros.
The Vax was one, IIRC. I'm afraid I'm going to be in the minority
again, but I viewed this as feature rather than flaw, since many
programs have a line like
if (foop && *foop) woo(foop);
which can now be replaced with a shorter construct.
Of course, *NULL was write-protected.


Yes. Returning to the thread's context, I think we all agree that
malloc()'ed memory should be written before read!

BTW, printf() will return a negative value ``if [and
only if] an output error is encountered.'' Do we insist on
checking for that every time printf() is called? Catching
that error is more relevant since it could be undetected, while,
in nearly all circumstances, a failed malloc() will quickly cause
a fault.

When you're crossing a busy street, do you stare at the heavens,
alert for a falling meteor you'll need to dodge? I thought not.
Similarly, any time wasted on errors that won't happen, is time
that could have been spent more usefully.

James
Nov 14 '05 #20
jd*********@yahoo.com (James Dow Allen) writes:
Kenneth Brody <ke******@spamcop.net> wrote in message
news:<41***************@spamcop.net>...
I've seen systems that allow you to dereference (for reading) a NULL
pointer, and that memory always contained zeros.


The Vax was one, IIRC. I'm afraid I'm going to be in the minority
again, but I viewed this as feature rather than flaw, since many
programs have a line like
if (foop && *foop) woo(foop);
which can now be replaced with a shorter construct.


Yes, I think you're in the minority on this one. 8-)}

I could see your point if the standard actually required this
behavior. But instead, too many programmers used the "shorter
construct", which worked just fine on the VAX, but failed mysteriously
as soon as the code was ported to another system.

Allowing null pointers to be dereferenced is not so much a convenience
as a way to postpone error detection.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #21
RoSsIaCrIiLoIA <n@esiste.ee> writes:

Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"

a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }


FWIW, this way of writing the checks and the relevant free() calls might
call free() with a pointer that hasn't been allocated. For instance, if
the first two malloc() calls succeed but the third fails, then free(c)
is not so safe. I'd probably write this as:

a = b = c = d = NULL;
if ((a = malloc(foo)) != NULL && (b = malloc(bar)) != NULL &&
(c = malloc(baz)) != NULL && (b = malloc(foobar)) != NULL) {
if (a != NULL) free(a);
if (b != NULL) free(b);
if (c != NULL) free(c);
if (d != NULL) free(d);
return -ENOMEM;
}

/* Do stuff. */
return 0;

Giorgos

Nov 14 '05 #22
Giorgos Keramidas <ke******@ceid.upatras.gr> wrote:
RoSsIaCrIiLoIA <n@esiste.ee> writes:

Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"

a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }


FWIW, this way of writing the checks and the relevant free() calls might
call free() with a pointer that hasn't been allocated.


Yes, but it's been set to null before the malloc() chain. Unlike normal
free() calls on non-allocated pointers, free(0) is safe - it's an
explicit requirement in the Standard.

Richard
Nov 14 '05 #23
On 26 Jul 2004 11:41:29 +0300, Giorgos Keramidas wrote:
RoSsIaCrIiLoIA <n@esiste.ee> writes:
Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"
a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }
FWIW, this way of writing the checks and the relevant free() calls might
call free() with a pointer that hasn't been allocated. For instance, if
the first two malloc() calls succeed but the third fails, then free(c)
is not so safe. I'd probably write this as:


if a=malloc(.) is Ok but b=malloc(..) is not Ok then
a=0; b=0; c=0; d=0;
if( (a=malloc(.)) && /* is ok because a!=0 */
(b=malloc(..)) && /* here b==NULL==0? so go to else */
...........................
)
else { free(a); /* ok allocated*/
free(b); /* ok b==NULL==0 */
free(c); free(d); /* ok c==0 d==0 ? better free((void*) c)? */
}
where is the error?
a = b = c = d = NULL;
if ((a = malloc(foo)) != NULL && (b = malloc(bar)) != NULL &&
(c = malloc(baz)) != NULL && (b = malloc(foobar)) != NULL) {
if (a != NULL) free(a);
if (b != NULL) free(b);
if (c != NULL) free(c);
if (d != NULL) free(d);
return -ENOMEM;
}

/* Do stuff. */
return 0;

Giorgos


Nov 14 '05 #24
RoSsIaCrIiLoIA <n@esiste.ee> writes:
a=0; b=0; c=0; d=0;
if( (a=malloc(.)) && /* is ok because a!=0 */
(b=malloc(..)) && /* here b==NULL==0? so go to else */
...........................
)
else { free(a); /* ok allocated*/
free(b); /* ok b==NULL==0 */
free(c); free(d); /* ok c==0 d==0 ? better free((void*) c)? */
}
where is the error?


No error, apologies. As it has been pointed out to me, I've missed a
very important part of the way free() works. Calling free(ptr) when
(ptr == NULL) is ok.

Nov 14 '05 #25
Giorgos Keramidas <ke******@ceid.upatras.gr> wrote:
RoSsIaCrIiLoIA <n@esiste.ee> writes:

Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"

a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }
FWIW, this way of writing the checks and the relevant free() calls might
call free() with a pointer that hasn't been allocated.


More precisely, it may call free with a null pointer argument.
For instance, if
the first two malloc() calls succeed but the third fails, then free(c)
is not so safe.
Nope, see below.
I'd probably write this as:

a = b = c = d = NULL;
if ((a = malloc(foo)) != NULL && (b = malloc(bar)) != NULL &&
(c = malloc(baz)) != NULL && (b = malloc(foobar)) != NULL) {
if (a != NULL) free(a);
if (b != NULL) free(b);
if (c != NULL) free(c);
if (d != NULL) free(d);

<snip>

These four checks are pointless, since passing a null pointer to
free() is well defined: it results in a no-op. Having said this,
you may of course use the checks as some form of weird micro-
optimization in error handling code... ;-)

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc OT guide : http://benpfaff.org/writings/clc/off-topic.html
Nov 14 '05 #26
Irrwahn Grausewitz <ir*******@freenet.de> wrote in message news:<1m********************************@4ax.com>. ..
Giorgos Keramidas <ke******@ceid.upatras.gr> wrote:
RoSsIaCrIiLoIA <n@esiste.ee> writes:

Yes, excuse but when I have seen the message I have thought "what I
could do in this case?"

a=0; b=0; c=0; d=0;
if(
(a = malloc(.)) &&
(b = malloc(..)) &&
(c = malloc(...))&&
(d = malloc(....)) )
;
else {free(a); free(b); free(c); free(d);... }


FWIW, this way of writing the checks and the relevant free() calls might
call free() with a pointer that hasn't been allocated.


More precisely, it may call free with a null pointer argument.
For instance, if
the first two malloc() calls succeed but the third fails, then free(c)
is not so safe.


Nope, see below.
I'd probably write this as:

a = b = c = d = NULL;
if ((a = malloc(foo)) != NULL && (b = malloc(bar)) != NULL &&
(c = malloc(baz)) != NULL && (b = malloc(foobar)) != NULL) {
if (a != NULL) free(a);
if (b != NULL) free(b);
if (c != NULL) free(c);
if (d != NULL) free(d);

<snip>

These four checks are pointless, since passing a null pointer to
free() is well defined: it results in a no-op. Having said this,
you may of course use the checks as some form of weird micro-
optimization in error handling code... ;-)

What Optiminzation dude?

--
Imanpreet Singh Arora
isingh AT acm DOT org
Nov 14 '05 #27
mi************@yahoo.com (Minti) writes:
Irrwahn Grausewitz <ir*******@freenet.de> wrote in message
news:<1m********************************@4ax.com>. ..
Giorgos Keramidas <ke******@ceid.upatras.gr> wrote: [...]
I'd probably write this as:

a = b = c = d = NULL;
if ((a = malloc(foo)) != NULL && (b = malloc(bar)) != NULL &&
(c = malloc(baz)) != NULL && (b = malloc(foobar)) != NULL) {
if (a != NULL) free(a);
if (b != NULL) free(b);
if (c != NULL) free(c);
if (d != NULL) free(d);

<snip>

These four checks are pointless, since passing a null pointer to
free() is well defined: it results in a no-op. Having said this,
you may of course use the checks as some form of weird micro-
optimization in error handling code... ;-)


What Optiminzation dude?


To take a simpler example, suppose p is a pointer whose value is the
result of a call to malloc(), but we don't know whether the call was
successful or not. So p could be either a null pointer or a pointer
to a chunk of allocated memory.

The following:

free(p);

is perfectly valid, since free() allows its argument to be a null
pointer (it does nothing in this case, since there's nothing to
deallocate).

On the other hand, the following:

if (p != NULL) {
free(p);
}

is also perfectly valid. The only difference is that the latter
avoids the call to free() if p is a null pointer. If p is a null
pointer, this saves the overhead of a function call. If p is
non-null, it has the overhead of an extra comparison. Which of these
is more efficient is going to depend on several things (the overhead
of the comparison, the overhead of a function call, the probability
that p is non-null, and possibly some extremely system dependent
concerns about cache usage, branch prediction, instruction pipelining,
and whatever else I haven't thought of).

It's unlikely that the optimization is going to be significant. If it
were, the implementation would be free (sic) to define free() as a
macro that avoids the function call if the argument is a null pointer.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #28

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

Similar topics

31
by: Caroline | last post by:
What is MALLOC exactly? Where is it used? Can someone please provide me with descriptive examples? Thank you
11
by: Mannequin* | last post by:
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to...
25
by: H.A. Sujith | last post by:
If malloc fails what should I do? 1. Exit imediately. 2. Print an error message (or put a log entry) and exit. 3. Print an error message (or put a log entry) and continue execution (after...
40
by: ramu | last post by:
Hi, what happens when i run the below code? main() { int *p; while(1) p= (int *)malloc(1000); } Do i get segmentation fault?
34
by: niranjan.singh | last post by:
This is regarding to test an SDK memory stuff. In what situation malloc gets fail. any comment/reply pls.... regards
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.