473,666 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4261
Chess Saurus <ch********@yah oo.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)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #2
In <e7************ **************@ posting.google. com> ch********@yaho o.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_FAILU RE); /* 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********@yah oo.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_FAILU RE);

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********@yaho o.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********@yah oo.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**********@n ewsg4.svr.pol.c o.uk>,
"Malcolm" <ma*****@55bank .freeserve.co.u k> wrote:
"Chess Saurus" <ch********@yah oo.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.u k> writes:
"Chess Saurus" <ch********@yah oo.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_Keit h) 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********@yaho o.com (Chess Saurus) wrote in message news:<e7******* *************** ****@posting.go ogle.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

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

Similar topics

31
3599
by: Caroline | last post by:
What is MALLOC exactly? Where is it used? Can someone please provide me with descriptive examples? Thank you
11
2405
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 follow? Second, have I correctly passed the structure's pointer to the functions in this program?
25
5064
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 possibly recovering from the error). Printing an error message might be difficult in a graphical environment. --
40
540
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
13372
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
8445
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8781
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8551
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8640
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7386
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5664
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2771
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
2
1776
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.