473,544 Members | 1,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to check the return value of malloc

Howdy,

I was reflecting recently on malloc.

Obviously, for tiny allocations like 20 bytes to strcpy a filename or
something, there's no point putting in a check on the return value of
malloc.

OTOH, if you're allocating a gigabyte for a large array, this might
fail, so you should definitely check for a NULL return.

So somewhere in between these extremes, there must be a point where you
stop ignoring malloc's return value, and start checking it.

Where do people draw this line? I guess it depends on the likely system
the program will be deployed on, but are there any good rule-of-thumbs?

Rgds,
MJ

Jan 18 '08
173 7942
On Fri, 18 Jan 2008 23:41:49 -0600, user923005 wrote
(in article
<a1************ *************** *******@z17g200 0hsg.googlegrou ps.com>):
On Jan 18, 7:39*pm, CBFalconer <cbfalco...@yah oo.comwrote:
>Randy Howard wrote:
>>Eric Sosman wrote
Marty James wrote:
>>>>I was reflecting recently on malloc.
>>>>Obviously , for tiny allocations like 20 bytes to strcpy a
filename or something, there's no point putting in a check on
the return value of malloc.
>>>* * *"Obviously, " you can allocate an infinite amount of
memory as long as you get it in 20-byte chunks? *Did you
used to work for Enron or something?
>>This thread was useful, now I know I never have to buy extra
memory again.

PROVIDED you malloc it in 20 byte chunks. *Since the standard
specifies that freed memory be made available again, you must be
perfectly safe in allocating 4k by:

* *for (i = 0; i < 20; i++) a[i] = malloc(20);
* *for (i = 0; i < 20; i++) free(a[i]);
* *ptr = malloc(4000);

with suitable declarations for a, i, ptr, and all the needed
#includes. *Learning is wunnerful.

You might be perfectly safe to allocate (say) 64K according to the ISO
C Standard. But the other program that is running and has consumed
all but 19 free bytes before your program executes the first malloc()
doesn't know that.
Both of you need to get a sense of humor. :)

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

Jan 19 '08 #21

"Marty James" <ma**@nospam.co mwrote in message
news:sl******** ***********@nos pam.invalid...
Howdy,

I was reflecting recently on malloc.

Obviously, for tiny allocations like 20 bytes to strcpy a filename or
something, there's no point putting in a check on the return value of
malloc.

OTOH, if you're allocating a gigabyte for a large array, this might
fail, so you should definitely check for a NULL return.

So somewhere in between these extremes, there must be a point where you
stop ignoring malloc's return value, and start checking it.

Where do people draw this line? I guess it depends on the likely system
the program will be deployed on, but are there any good rule-of-thumbs?
If checking is that much trouble then create a wrapper function around
malloc() that will always return a valid result. (The wrapper will check for
NULL results of malloc() and abort or do other exception code.) Then call
that instead of malloc(). This way you dispense with checking every time.

Use this when allocation failure is (a) unimportant or (b) very important
(that the program cannot proceed). (Seems paradoxical I know.)

To take some other action when allocation fails then call malloc() in the
regular way.

Bart

Jan 19 '08 #22

"Marty James" <ma**@nospam.co mwrote in message
Obviously, for tiny allocations like 20 bytes to strcpy a filename or
something, there's no point putting in a check on the return value of
malloc.

OTOH, if you're allocating a gigabyte for a large array, this might
fail, so you should definitely check for a NULL return.

So somewhere in between these extremes, there must be a point where you
stop ignoring malloc's return value, and start checking it.

Where do people draw this line? I guess it depends on the likely system
the program will be deployed on, but are there any good rule-of-thumbs?
Yes.
Imagine you've got 2GB installed and are allocating 20 bytes. The system is
stressed and programs crash or terminate for lack of memory once a day. Any
more than that, and no-one would tolerate it.
So the chance the crash being caused by your allocation is 1/ 100 000 000,
or once every several hundred thousand years. The chance of the computer
breaking during this period is so so much higher, there is in this case no
point checking the malloc().

It is elementary. When you control the quality of a part, and there are
costs - here increased complexity of code, thus maintenance costs - the
quality should be high enough that your part is unlikely to the the point of
failure, but no higher.

As others have pointed out, if your main allocation is in a loop, the
probabilities have to be adjusted accordingly.

You might be interestwed in xmalloc(), on my website, which gets round this
problem of too much error-handling code which will never be executed. For
all I have said, there is also a case for making programs which are correct.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Jan 19 '08 #23
Keith Thompson wrote:
There's an old saying: Never check for an error condition you don't
know how to handle.

But if you can't figure out what to do, you can always just terminate
the program. It's not necessarily the best thing you can do, but it's
the second simplest, and it's almost certainly better than the
simplest (ignoring the error).
Well, I don't usually check the result of a call such as
fprintf(stderr, "Can't frobnicate %s: %s\n", frob, strerror(errno) ),
because I don't know what should I do if it failed, but I don't think that
just terminating the program would be a good idea (unless I were going to
terminate it right after the fprintf regardless of its success, that is).
--
Army1987 (Replace "NOSPAM" with "email")
Jan 19 '08 #24
Malcolm McLean wrote, On 19/01/08 10:47:
>
"Marty James" <ma**@nospam.co mwrote in message
>Obviously, for tiny allocations like 20 bytes to strcpy a filename or
something, there's no point putting in a check on the return value of
malloc.

OTOH, if you're allocating a gigabyte for a large array, this might
fail, so you should definitely check for a NULL return.

So somewhere in between these extremes, there must be a point where you
stop ignoring malloc's return value, and start checking it.

Where do people draw this line? I guess it depends on the likely system
the program will be deployed on, but are there any good rule-of-thumbs?
Yes.
Imagine you've got 2GB installed and are allocating 20 bytes. The system
is stressed and programs crash or terminate for lack of memory once a
day. Any more than that, and no-one would tolerate it.
So the chance the crash being caused by your allocation is 1/ 100 000
000, or once every several hundred thousand years. The chance of the
computer breaking during this period is so so much higher, there is in
this case no point checking the malloc().
This is incredibly bad advice. It has also been pointed out to Malcolm
in the past that it is incredibly bad advice.

I run out of memory on my company notebook with 2GB of RAM. I know
people run out of memory on servers with far more than 2GB of RAM. In
fact, I don't think I've had a month when some piece of SW has not
reported being out of memory and provided a recovery mechanism.

<snip>
You might be interestwed in xmalloc(), on my website, which gets round
this problem of too much error-handling code which will never be
executed. For all I have said, there is also a case for making programs
which are correct.
I would suggest looking very carefully at any malloc wrapper before
using it. You need to decide whether aborting on failure is appropriate
or some recovery strategy.
--
Flash Gordon
Jan 19 '08 #25
Malcolm McLean wrote:
You might be interestwed in xmalloc(), on my website[1], which gets round
this problem of too much error-handling code which will never be executed.
I took a look at it. Apart from being too complicated for most programs
(yes, some will actually be able to use the additional complexity), it has
one IMHO grave bug: it uses 'int' for the allocation size. Use size_t,
which is the correct type, or do you check if the result of 'strlen()' can
be safely converted to an 'int' before calling your 'xmalloc()'?

- sorry, no chocolate for you -

Uli

[1] http://www.personal.leeds.ac.uk/~bgy...c/xmalloc.html

Jan 19 '08 #26

"Flash Gordon" <sp**@flash-gordon.me.ukwro te in message
This is incredibly bad advice. It has also been pointed out to Malcolm in
the past that it is incredibly bad advice.
Advice is a dangerous gift, even from the wise to the wise.
>
I run out of memory on my company notebook with 2GB of RAM. I know people
run out of memory on servers with far more than 2GB of RAM. In fact, I
don't think I've had a month when some piece of SW has not reported being
out of memory and provided a recovery mechanism.
Yes, but not very often on a single allocation of 20 bytes. That will happen
once
in every 100 000 000 months on such a machine.
>
>You might be interestwed in xmalloc(), on my website, which gets round
this problem of too much error-handling code which will never be
executed. For all I have said, there is also a case for making programs
which are correct.

I would suggest looking very carefully at any malloc wrapper before using
it. You need to decide whether aborting on failure is appropriate or some
recovery strategy.
xmalloc() never returns null, so there is no need to provide error-checking.
Basically the idea is to get clutter which will never be executed out of
functions, so that normal logic flow stands out more clearly.
Obviously you cannot guarantee an infitie supply of memory. So by default
xmalloc() aborts with an error message. That's because there is not much
else you can do within the constraints of ANSI C.
However the failure handler can be reset, and I have one for X which
requests that the user terminate some other application. Again, that isn't
approriate for everything - a server, for instance, could release memory
from an emergency store, and then put itself into "critical please attend to
me mode".
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jan 19 '08 #27

"Ulrich Eckhardt" <do******@knuut .dewrote in message
Malcolm McLean wrote:
>You might be interestwed in xmalloc(), on my website[1], which gets round
this problem of too much error-handling code which will never be
executed.

I took a look at it. Apart from being too complicated for most programs
(yes, some will actually be able to use the additional complexity), it has
one IMHO grave bug: it uses 'int' for the allocation size. Use size_t,
which is the correct type, or do you check if the result of 'strlen()' can
be safely converted to an 'int' before calling your 'xmalloc()'?

- sorry, no chocolate for you -
If the amount of memory won't fit into an int you probably shouldn't be
calling the function. It is for small amounts of memory, and is compatible
with the original C specification of malloc().

Also, using a signed value means that we can pick up many bugs. If garbage
is passed to malloc() then 50% of the time the argument will be negative.
Assuming randomness, if the function is called more than once or twice, you
practically have a guarantee of catching the bug.

I can't do anything about the size_t returned from strlen. It is most
unlikely that you'll have strings of more than the range of an int, and a
lot of people complain at use of high bit types - that's the objection, and
it is a legitimate one, made most often to the campaign for 64 bit ints.

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

Jan 19 '08 #28
user923005 wrote:
CBFalconer <cbfalco...@yah oo.comwrote:
>Randy Howard wrote:
>>Eric Sosman wrote
Marty James wrote:
>>>>I was reflecting recently on malloc.
>>>>Obviously , for tiny allocations like 20 bytes to strcpy a
filename or something, there's no point putting in a check on
the return value of malloc.
>>> "Obviously, " you can allocate an infinite amount of
memory as long as you get it in 20-byte chunks? Did you
used to work for Enron or something?
>>This thread was useful, now I know I never have to buy extra
memory again.

PROVIDED you malloc it in 20 byte chunks. Since the standard
specifies that freed memory be made available again, you must be
perfectly safe in allocating 4k by:

for (i = 0; i < 20; i++) a[i] = malloc(20);
for (i = 0; i < 20; i++) free(a[i]);
ptr = malloc(4000);

with suitable declarations for a, i, ptr, and all the needed
#includes. Learning is wunnerful.

You might be perfectly safe to allocate (say) 64K according to
the ISO C Standard. But the other program that is running and
has consumed all but 19 free bytes before your program executes
the first malloc() doesn't know that.
No, you haven't been following. The OP postulated that assignment
of 20 bytes was safe, and needed no checking. He wanted to know a
level that needed checking. I was pointing out that his original
assumption obviated the need for ANY checking of malloc.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.

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

Jan 19 '08 #29
Malcolm McLean wrote, On 19/01/08 13:44:
>
"Flash Gordon" <sp**@flash-gordon.me.ukwro te in message
>This is incredibly bad advice. It has also been pointed out to Malcolm
in the past that it is incredibly bad advice.
Advice is a dangerous gift, even from the wise to the wise.
Irrelevant. Your advice was bad for anyone whether they recipient is
wise or not.
>I run out of memory on my company notebook with 2GB of RAM. I know
people run out of memory on servers with far more than 2GB of RAM. In
fact, I don't think I've had a month when some piece of SW has not
reported being out of memory and provided a recovery mechanism.
Yes, but not very often on a single allocation of 20 bytes. That will
happen once
in every 100 000 000 months on such a machine.
If my machine is out of memory then an allocation request for ONE byte
will fail, that it is other programs using up all of the memory is
irrelevant. I run out of memory on my machine regularly as stated.
Fortunately even MS seems to have a better understanding of this than you.
>>You might be interestwed in xmalloc(), on my website, which gets
round this problem of too much error-handling code which will never
be executed. For all I have said, there is also a case for making
programs which are correct.

I would suggest looking very carefully at any malloc wrapper before
using it. You need to decide whether aborting on failure is
appropriate or some recovery strategy.
xmalloc() never returns null, so there is no need to provide
<snip>

So are you claiming that the OP should not look carefully at the malloc
wrapper and deciding on the appropriate strategy for his/her
application? If not I don't see the point of that message.
--
Flash Gordon
Jan 19 '08 #30

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

Similar topics

27
4713
by: MK | last post by:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux): ================================================================== read_raw_data.c:51: warning: assignment makes pointer from integer without a cast ================================================================== when the following piece of...
10
2181
by: raghu | last post by:
I have written code for single linked list...I get an error as Expression syntax in the line marked with ////////. Please correct me where am I going wrong. I compiled this in TURBO Compiler #include<stdio.h> #include<alloc.h> struct node { int data; struct node *link;
58
4611
by: Jorge Peixoto de Morais Neto | last post by:
I was reading the code of FFmpeg and it seems that they use malloc just too much. The problems and dangers of malloc are widely known. Malloc also has some overhead (although I don't know what is the overhead of automatic variable sized arrays, I suspect it is smaller than that of malloc), although I'm not too worried about it. I was...
0
7426
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7368
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7610
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7774
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
4920
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3412
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1843
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
989
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
667
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.