473,320 Members | 1,976 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,320 software developers and data experts.

If malloc fails

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.

--
mail to: randomzoo <at> spymac <dot> com
Nov 14 '05 #1
25 5026
On Mon, 19 Jul 2004, H.A. Sujith wrote:

HS>If malloc fails what should I do?
HS>
HS>1. Exit imediately.
HS>2. Print an error message (or put a log entry) and exit.
HS>3. Print an error message (or put a log entry) and continue
HS>execution (after possibly recovering from the error).

That depends stronlgy on the concrete application. For one-shot programs
like 'ls' or so a malloc() failure is most probable a problem in the
environment and just printing a message (if possible) and exiting is the
best one can do. For programs that are long running or run under special
conditions (think of controlling software for a nuclear power plant) this
is not an option and they probably have to try to recover (and log, of
course).

HS>Printing an error message might be difficult in a graphical environment.

That's one of the reasons why such programs sometimes simply disappear
from the screen without any hint what happend.

harti
Nov 14 '05 #2
On Mon, 19 Jul 2004, H.A. Sujith wrote:
If malloc fails what should I do?

1. Exit imediately.
Maybe.
2. Print an error message (or put a log entry) and exit.
Maybe.
3. Print an error message (or put a log entry) and continue
execution (after possibly recovering from the error).
Maybe.

The answer all depends on the situation. If IO absolutely must have a
successful malloc or there is not point continuing then I would exit. If
I'm attempt to allocate a large block of memory but can get by with a
smaller block then adjust and keep going.

Do I print an error message? Depends on the environment. If the program is
going to be used in an automated or embedded system then I would not print
an error message (there will be no human to see it). If the application is
always going to be run interactively then I would print an error message.
Printing an error message might be difficult in a graphical environment.


Why? If it is just because you have to go through the effort of creating a
dialog then learn to create a dialog. If it is because a failed malloc
means there isn't enough memory to display an error dialog, see if there
is a system level way of printing an error message. Often the OS will
reserve memory for printing critical error dialogs. If your OS does not do
this, allocate enough memory right at the start so there is memory to
print an error dialog. Keep that memory in reserve until you quit the
application.

--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@whitehouse.gov
Nov 14 '05 #3
H.A. Sujith wrote:
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.


I have gone down the avenue of trying to make malloc() fail, and it's
easier said then done. Also, implementation specific settings have to
be set to create a possibility of malloc() failing. (e.g., RLIMIT_DATA
in linux, malloc.conf in BSD, etc.).

A good exercise would be just trying to get malloc() to fail under your
implementation to make sure the above items you listed even work. And
do not forget to allocate enough space for the trailing '\0'.

I have recently moved over to openBSD to experiment with making malloc()
fail. It's really implementation specific, so I'm curious what the
regulars here think about porting malloc() between platforms since there
doesn't seem to be a standard as to whether or not errno is set when
malloc() fails.

brian
Nov 14 '05 #4
"H.A. Sujith" wrote:

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).

[...]

It depends entirely on the situation.

For example, I have a report generator program which allocates memory (in
chunks) for sorting the selected records. If malloc fails after I have
already allocated at least one memory block, then it doesn't matter, and
I simply stop trying to allocate more memory, and use only the memory
that I already have. In this case, the answer is:

4. Continue running, but without the memory you tried to allocate.

Of course, if the first malloc fails, then it's a fatal error.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody at spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Nov 14 '05 #5
H.A. Sujith a formulé la demande :
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.


There is no definitive answer, and it's beyond the C-language itself.
It's more a specification and eventually design issue.

-> At some library level, I tend to return some information that a
problem occured (null pointer, error value etc.)

-> At application level, I tend to display some message (to stderr,
stdout, some log file, a message box in graphical environment, ...).
The exit is an option if the error is not recoverable. You could simply
retry later, or with a smaller amout if it doesn't hurt.

But to conclude, and to come back to the C-language, a pointer with a
null value must not be dereferenced.

--
Emmanuel

Nov 14 '05 #6

"H.A. Sujith" <su****@localhost.localdomain> wrote
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.

It depends what you are allocating. If you are allocating a few bytes, maybe
for a filename, on a large system then basically malloc() cannot fail. The
system will have issued "low on memory" warnings long before this happens.
However for the program to be correct, you still need to handle the failure.
Exit is perfectly reasonable.
However if you are allocating a very large data set, it is entirely possible
that the computer is genuinely out of memory. So you need to tell the user
what has happened, and allow him to close other applications and retry, or
do whatever else is necessary to recover.
Nov 14 '05 #7
On 19 Jul 2004 08:45:18 -0700, in comp.lang.c , "H.A. Sujith"
<su****@localhost.localdomain> wrote:
If malloc fails what should I do?
Whatever is most appropriate for your application.
1. Exit imediately.
2. Print an error message (or put a log entry) and exit.
neither very suitable for pacemakers, air traffic control systems etc.....
typically more ok for simple tools eg cat, cp.
3. Print an error message (or put a log entry) and continue
execution (after possibly recovering from the error).
may not be possible, but graceful cleanup is advisable.
Printing an error message might be difficult in a graphical environment.


There's usually a system-specific way to flag fatal errors which uses
reserved system memory and is thus not subject to your own malloc woe.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #8
In article <sl*******************@localhost.localdomain>,
"H.A. Sujith" <su****@localhost.localdomain> wrote:
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.


You look at it from the programmer's point of view. You should look at
it from the user's point of view. What are the consequences for the user
of your software of your action? What can you do or what do you have to
do to improve these consequences?

If I spent twelve hours editing a document, choose "Save" from a menu,
and the program runs out of memory just at this point and exits (after
printing an error message or not) without saving twelve hours of my
work, then the programmer responsible deserves to be shot.
Nov 14 '05 #9
"Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
"H.A. Sujith" <su****@localhost.localdomain> wrote
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.

If you're in a graphical environment, presumably you have some way of
displaying a message, perhaps by popping up a dialog window.
It depends what you are allocating. If you are allocating a few bytes, maybe
for a filename, on a large system then basically malloc() cannot fail. The
system will have issued "low on memory" warnings long before this happens.


You're assuming that malloc() will fail only if the entire system is
running low on memory. Many systems place limits on the memory
allocated by a single program; a program can hit those limits long
before the system as a whole is in trouble.

Even if the entire system is running low on memory, it's unlikely that
a given program will be aware of any "low on memory" warnings that the
system might have generated. If the system has 10 bytes left to
allocate, and a program asks for 20, the allocation will fail.
Obviously a large request is more likely to fail than a small one, but
it's always possible that a 1-byte request will be the straw that
breaks the camel's back.

As for recovery strategies, it's seldom sensible for a program to try
to continue whatever task it was working on after a malloc() failure.
Whether aborting the task means aborting the entire program depends on
the nature of the program.

If the program has built up a lot of valuable information, it should
try to save it before aborting. (For example, if a text editor
doesn't have enough memory to insert another character into the
buffer, it shouldn't bail out and throw away the whole buffer.)

There is no universal answer.

--
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 #10

"Christian Bau" <ch***********@cbau.freeserve.co.uk> wrote in message
news:ch*********************************@slb-newsm1.svr.pol.co.uk...
In article <sl*******************@localhost.localdomain>,
"H.A. Sujith" <su****@localhost.localdomain> wrote:
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.


You look at it from the programmer's point of view. You should look at
it from the user's point of view. What are the consequences for the user
of your software of your action? What can you do or what do you have to
do to improve these consequences?

If I spent twelve hours editing a document, choose "Save" from a menu,
and the program runs out of memory just at this point and exits (after
printing an error message or not) without saving twelve hours of my
work, then the programmer responsible deserves to be shot.


Totally agree.

If there is a chance somebody wasted a lot of time with the program,
exit() is not an option.
Nov 14 '05 #11
>> > Printing an error message might be difficult in a graphical environment.

If you're in a graphical environment, presumably you have some way of
displaying a message, perhaps by popping up a dialog window.


The error-retentive approach to this is that if you run out of
memory trying to create a dialog window, you MUST report it by
trying to create a dialog window. When that fails, you must report
that also. Similarly, you MUST report all failures to write a
message on stderr with an error message on stderr, thereby ensuring
that if the disk ever fills up, it will STAY filled up.
It depends what you are allocating. If you are allocating a few bytes, maybe
for a filename, on a large system then basically malloc() cannot fail. The
system will have issued "low on memory" warnings long before this happens.


What is the return value from malloc() that constitutes a "low memory"
warning?

Gordon L. Burditt
Nov 14 '05 #12
brian wrote:
there
doesn't seem to be a standard as to whether or not errno is set when
malloc() fails.


SUSv3 has this to say:

---
RETURN VALUE

Upon successful completion with size not equal to 0, malloc() shall
return a pointer to the allocated space. If size is 0, either a null
pointer or a unique pointer that can be successfully passed to free()
shall be returned. Otherwise, it shall return a null pointer [CX]
and set errno to indicate the error.
---

The setting of errno is a SUS extension to ISO C. However, the errno
mandated by SUSv3 is not too useful: only ENOMEM is specified.

--
Arto Huusko
Nov 14 '05 #13

"Gordon Burditt" <go***********@burditt.org> wrote
It depends what you are allocating. If you are allocating a few bytes,
maybe for a filename, on a large system then basically malloc() cannot fail. The system will have issued "low on memory" warnings long before this
happens.


What is the return value from malloc() that constitutes a "low memory"
warning?

We're talking about allocating a few bytes, maybe for a file name, on a
system with many megabytes available.
For malloc() to fail in these circumstances the pool of memory available to
the program must be extremely low. Now a decent OS will not allow this to
happen in the absence of warning. For instance the system may start running
very slowly because of excessive use of swap space, or there may be warning
messages sent to the user. Only if the user fails to respond to these
symptoms will malloc() actually fail.
So handling the failure is a formality only, and there is not much point
uglifying code for an error condition which will never be encountered. So an
abort is reasonable. In fact the most likely cause of failure is probably a
programming error causing a garbage value to be passed to malloc() (if
strlen doesn't have a prototype in scope and size_t isn't an unsigned int,
for example). Once a program is incorrect, there's very little you can do.

However if you are allocating a large amount of memory, then it is likely
that malloc() may fail, so the above doesn't apply.
Nov 14 '05 #14
"Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
"Gordon Burditt" <go***********@burditt.org> wrote
> It depends what you are allocating. If you are allocating a few
> bytes, maybe for a filename, on a large system then basically
> malloc() cannot fail. The system will have issued "low on
> memory" warnings long before this happens.


What is the return value from malloc() that constitutes a "low memory"
warning?

We're talking about allocating a few bytes, maybe for a file name, on a
system with many megabytes available.
For malloc() to fail in these circumstances the pool of memory available to
the program must be extremely low. Now a decent OS will not allow this to
happen in the absence of warning. For instance the system may start running
very slowly because of excessive use of swap space, or there may be warning
messages sent to the user. Only if the user fails to respond to these
symptoms will malloc() actually fail.
So handling the failure is a formality only, and there is not much point
uglifying code for an error condition which will never be encountered. So an
abort is reasonable. In fact the most likely cause of failure is probably a
programming error causing a garbage value to be passed to malloc() (if
strlen doesn't have a prototype in scope and size_t isn't an unsigned int,
for example). Once a program is incorrect, there's very little you can do.

However if you are allocating a large amount of memory, then it is likely
that malloc() may fail, so the above doesn't apply.


You're making a lot of unwarranted assumptions.

You're assuming that if malloc() fails, it's because the system as a
whole is short on memory. On many systems, a single process can run
out of memory long before the entire system is having any problems.

You're assuming that "the user" is going to respond to a low memory
warning. On a server, there may not be a user who's able to respond
immediately. On a multi-user system, the user running a particular
program may not be able to do anthing about a warning (if he sees it)
other than notifying an administrator, who may or may not be available
at the moment. And depending on the reason for the low memory
condition, there may not be time to respond between the initial
warning and a crash.

Even if there's a single user able to respond to low memory warning,
the user's failure to do so doesn't relieve the program of its
responsibility to respond properly when memory actually runs out.

If a call to malloc() fails, the program needs to detect the failure
and do whatever recovery is appropriate; the size of the request is
irrelevant. If my text editor, for example, aborts and throws away my
changes on a malloc() failure, I'm not going to be interested in
hearing that it didn't bother recovering because it was only
requesting enough memory for a file name.

--
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
kal
"H.A. Sujith" <su****@localhost.localdomain> wrote in message news:<slrncfnh80.7rf.su****@localhost.localdomain> ...
If malloc fails what should I do?
Go fishing.

malloc does not fail unless the system as a whole is crashing.
It either allocates or does not allocate memory. As has been
pointed out in numerous threads on here, it is a good practice
to test the return value of malloc. By testing, it is meant
that if memory has not been allocated then a different set of
operations will be executed by the program. What those
operations are depends on who is buying your program.
1. Exit imediately.
NO. The only situation in which this is acceptable is that
the program is not able to initialize itself. But such
conditions are outside the scope of the program. Note that
every C program is guaranteed at least 32/64 KB of memory.
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).
Either or both, depending upon your proclivities. Or a number
of other alternatives. In all cases you MUST shut the program
down GRACEFULLY. Hopefully you had already allocated sufficient
resources required for program shutdown.

If you had not pre-allocated resourses required for program
shutdown then you are in exalted company; like Abhimanyu, who
knew how to get in and not how to get out.
Printing an error message might be difficult in a graphical environment.


Not at all. At the least you should have a "status bar" or some
such pre-allocated resource using which you can display messages.
(Note that "stderr" comes pre-allocated.)
Nov 14 '05 #16
Arto Huusko wrote:
brian wrote:
there
doesn't seem to be a standard as to whether or not errno is set when
malloc() fails.

SUSv3 has this to say:

---
RETURN VALUE

Upon successful completion with size not equal to 0, malloc() shall
return a pointer to the allocated space. If size is 0, either a null
pointer or a unique pointer that can be successfully passed to free()
shall be returned. Otherwise, it shall return a null pointer [CX]
and set errno to indicate the error.
---

The setting of errno is a SUS extension to ISO C. However, the errno
mandated by SUSv3 is not too useful: only ENOMEM is specified.

If the implementation follows the standards, the above is what I get
(that ENOMEN is set) from the malloc() man page in openBSD. However,
in the man page in linux, there was no mention of ENOMEM being set,
and I couldn't get malloc() to fail in linux even using setrlimit().

Now, you have to test for how much the implementation follows any
standard and what standards are followed, which makes portability a pain.

And per the scope of this newsgroup, any extension of ISO C is off
topic. So if the C standard does not require malloc() to set errno,
then we have serious problems when testing for errors. We first
have to determine what standard is followed. We then have to re-write
our error code by implementation or use a lot of #ifndef #if . . .

As you can see, you can find a lot of holes in "portable" software
when it's trying to be ported across a bunch of OS's. And the compiler
won't complain, so you have audit the code.

Brian

P.S. Of course, the definition of what RLIMIT_DATA means is different
between openBSD and linux.
Nov 14 '05 #17

"Keith Thompson" <ks***@mib.org> wrote in message

If a call to malloc() fails, the program needs to detect the failure
and do whatever recovery is appropriate; the size of the request is
irrelevant. If my text editor, for example, aborts and throws away my
changes on a malloc() failure, I'm not going to be interested in
hearing that it didn't bother recovering because it was only
requesting enough memory for a file name.

The problem is that if the system won't give you a hundred bytes for a file
name, will it give you the memory it needs to call fopen() or the save file
dialog?
Once you are totally out of heap then you are in trouble, unless the system
has been specifically written so that it can function without heap memory.
Anyway, say your program has 10MB of memory available. Given that the
program will run out of memory on a run, the chance of hundred byte
allocation being the one to straddle the boundary is 1 in a hundred
thousand. So if it's a text editor, taking several minutes to run, even if
it runs out of memory on every run, the computer is much more likely to
break than it is to execute your malloc() failure handling code. So no, we
don't need to bother too much what goes into that code.
Nov 14 '05 #18
On 20 Jul 2004 04:08:07 GMT, in comp.lang.c , go***********@burditt.org
(Gordon Burditt) wrote:
> Printing an error message might be difficult in a graphical environment.


If you're in a graphical environment, presumably you have some way of
displaying a message, perhaps by popping up a dialog window.


The error-retentive approach to this is that if you run out of
memory trying to create a dialog window, you MUST report it by
trying to create a dialog window.


(snip recursive attempt to display error windows).
Thats why a decent OS reserves enough memory to display warning/error
dialogs without invading user space.
It depends what you are allocating. If you are allocating a few bytes, maybe
for a filename, on a large system then basically malloc() cannot fail. The
system will have issued "low on memory" warnings long before this happens.


What is the return value from malloc() that constitutes a "low memory"
warning?


Well obviously,failure indicates a lower memory warning. How you handle
this is up to you

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #19
brian <xb**********@cox.net> wrote:
Arto Huusko wrote:
The setting of errno is a SUS extension to ISO C. However, the errno
mandated by SUSv3 is not too useful: only ENOMEM is specified.
If the implementation follows the standards, the above is what I get
(that ENOMEN is set) from the malloc() man page in openBSD. However,
in the man page in linux, there was no mention of ENOMEM being set,
and I couldn't get malloc() to fail in linux even using setrlimit().


See the NOTES section of the Linux man page, it's mentioned there.
Regarding your problem to get malloc() to fail lets discuss this in
comp.os.linux.development.apps, you can definitely get it to fail.
Now, you have to test for how much the implementation follows any
standard and what standards are followed, which makes portability a pain. And per the scope of this newsgroup, any extension of ISO C is off
topic. So if the C standard does not require malloc() to set errno,
then we have serious problems when testing for errors. We first
have to determine what standard is followed. We then have to re-write
our error code by implementation or use a lot of #ifndef #if . . .


I don't see why having errno set or not would be a problem at all -
just assume it won't get set and everything should be fine. There
isn't any additional information you get from checking errno you
don't already have when malloc() returns NULL.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #20
"Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
If a call to malloc() fails, the program needs to detect the failure
and do whatever recovery is appropriate; the size of the request is
irrelevant. If my text editor, for example, aborts and throws away my
changes on a malloc() failure, I'm not going to be interested in
hearing that it didn't bother recovering because it was only
requesting enough memory for a file name.
The problem is that if the system won't give you a hundred bytes for a file
name, will it give you the memory it needs to call fopen() or the save file
dialog?


So pre-allocate enough memory to do whatever cleanup is necessary.

One possible approach (I haven't tried this, so undoubtedly large
holes could be shot in the idea) might be to malloc() a medium-sized
chunk of memory during startup, maybe a few kilobytes. If a malloc()
fails, invoke a cleanup routine that first free()s this initial chunk,
providing enough free space to continue the cleanup before bailing out.

There's no guarantee that this would work.
Once you are totally out of heap then you are in trouble, unless the system
has been specifically written so that it can function without heap memory.
Anyway, say your program has 10MB of memory available. Given that the
program will run out of memory on a run, the chance of hundred byte
allocation being the one to straddle the boundary is 1 in a hundred
thousand. So if it's a text editor, taking several minutes to run, even if
it runs out of memory on every run, the computer is much more likely to
break than it is to execute your malloc() failure handling code. So no, we
don't need to bother too much what goes into that code.


I'd rather handle the error properly than gamble on the assumption
that it's unlikely.

--
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

Je***********@physik.fu-berlin.de wrote:
See the NOTES section of the Linux man page, it's mentioned there.
Regarding your problem to get malloc() to fail lets discuss this in
comp.os.linux.development.apps, you can definitely get it to fail.

I left off the headers and main() on the code below to focus on just the
code used to set up the constraint and the attempt to break it.

The method I used to attempt to get malloc to fail was:

char *ch = NULL;

struct rlimit r;
r.rlim_cur = 32;
r.rlim_max = 32;

/* sets the constraint on RLIMIT_DATA to 32 bytes */

if ( ( setrlimit(RLIMIT_DATA, &r) ) == -1 ) {
perror("setrlimit() error\n");
exit(EXIT_FAILURE);
}

/* attempts to allocate 4 * 64 bytes */

if ( (ch = malloc( sizeof(long) * 64) ) == NULL) {
perror("malloc() failed\n");
exit(EXIT_FAILURE);
}

free(ch);

Now, per the man page in linux for setrlimit, RLIMIT_DATA
should define the constraints on malloc() and related functions. Now,
the definition for RLIMIT_DATA is slightly different in BSD.

The biggest question is how memory is handled by the kernel. And
that is where I left the problem of trying to make malloc() fail in
linux. I haven't dug into virtual memory yet.

If I doubt malloc() will set errno, then I do not want
to use perror(). An assert() might work better.
I don't see why having errno set or not would be a problem at all -
just assume it won't get set and everything should be fine. There
isn't any additional information you get from checking errno you
don't already have when malloc() returns NULL.

Regards, Jens

True. But when you write your error code, you want to know whether
you want to print the STDERR stream or not. If I know that malloc()
will not set errno under different implementations, then I can just
check for NULL, write a printf() and exit().

The only applicable question to comp.lang.c is how to write error code
that is portable for malloc() and it's related functions. Of course,
setrlimit() is not defined by ISO C99.

Brian

P.S. Do you want me to cross post this response?
Nov 14 '05 #22
brian <xb**********@cox.net> wrote:
Je***********@physik.fu-berlin.de wrote:
> See the NOTES section of the Linux man page, it's mentioned there.
> Regarding your problem to get malloc() to fail lets discuss this in
> comp.os.linux.development.apps, you can definitely get it to fail.
I left off the headers and main() on the code below to focus on just the
code used to set up the constraint and the attempt to break it.

The method I used to attempt to get malloc to fail was:
Fine. But please take this to comp.os.linux.development.apps where
it is on-topic. Standard C doesn't have a setrlimit() function.
> I don't see why having errno set or not would be a problem at all -
> just assume it won't get set and everything should be fine. There
> isn't any additional information you get from checking errno you
> don't already have when malloc() returns NULL.

True. But when you write your error code, you want to know whether
you want to print the STDERR stream or not. If I know that malloc()
will not set errno under different implementations, then I can just
check for NULL, write a printf() and exit().


Well, you're absolutely safe if you don't care if malloc() sets errno
or not and just check the return value for NULL. The C standard does
not require malloc() to set errno, so don't rely on it and there are
are no portability problems at all. I really can't see your problem.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #23
Je***********@physik.fu-berlin.de wrote:
Fine. But please take this to comp.os.linux.development.apps where
it is on-topic. Standard C doesn't have a setrlimit() function.
I have already discussed this in comp.unix.programmer. But the op
question was how to write error code and exit code for malloc().
The answer is part implementation specific and part C99 specific.
And I said in my response that setrlimit() is off topic here.
Well, you're absolutely safe if you don't care if malloc() sets errno
or not and just check the return value for NULL. The C standard does
not require malloc() to set errno, so don't rely on it and there are
are no portability problems at all. I really can't see your problem.


If you don't care about errno, there is no portability problem If you
do, there might be a portability problem. Of course, you should test
your code to make sure the error code and/or exit code will be executed.

Brian
Nov 14 '05 #24

"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"Malcolm" <ma*****@55bank.freeserve.co.uk> writes:
The problem is that if the system won't give you a hundred bytes for a file name, will it give you the memory it needs to call fopen() or the save file dialog?
So pre-allocate enough memory to do whatever cleanup is necessary.

One possible approach (I haven't tried this, so undoubtedly large
holes could be shot in the idea) might be to malloc() a medium-sized
chunk of memory during startup, maybe a few kilobytes. If a malloc()
fails, invoke a cleanup routine that first free()s this initial chunk,
providing enough free space to continue the cleanup before bailing out.

There's no guarantee that this would work.

This is the sort of thing you've got to do. If fopen() calls malloc()
internally, for example, you have to either write your own file routine that
uses a static area of memory, or free enough memory (and know that it won't
be grabbed by another process). So the whole thing is rather tricky and
difficult.
I'd rather handle the error properly than gamble on the assumption
that it's unlikely.

You've got to decide how to allocate programming resources. If you're
writing control systems for a nuclear power station, or even a text editor
for Microsoft, then it is probable that development costs don't matter. If
you're writing a video game then costs, and, even more so, time really does
matter.
Now if you are allocating a 100 bytes on a 10MB system, and memory is being
allocated in a lot of smallish chunks at random, and your program runs out
of memory, then the chnace that it will run out of memory during the 100
byte allocation is 1 in 100000.
Let's suppose the computer runs out of memory every ten minutes, or 150
times a day. That means you can run for 666 days, or about two years,
before the code will be ever executed. It is unlikely that a desktop
computer can run for two years continuously without some sort of mechanical
failure. There will also be software failures - my copy of Windows certainly
can't run for two years without crashing.
Then you've got the problem that you need some sort of fancy memory scheme
to cope with having no core left anyway. The whole idea of handling the
error suddenly seems a lot less attractive.
Nov 14 '05 #25
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote:
"H.A. Sujith" <su****@localhost.localdomain> wrote
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).
I'll go with the "it depends answers" that others have posted.
Fundamentally you have to decide on an error policy for your program,
then just follow it.
Printing an error message might be difficult in a graphical environment.
It depends what you are allocating. If you are allocating a few bytes, maybe
for a filename, on a large system then basically malloc() cannot fail.


What? There is no way you can predict the size of the straw that
breaks the camel's back. This is also a system/platform assumption
that is quite possibly incorrect. Certain "poor heap architectures"
such as the one used in the original UNIX platform (and which
apparently SCO still uses) can accumlate "lost blocks" -- meaning that
any successive random sequence of allocations regardless of size will
eventually exhaust the heap. Another possibility is that in a
multi-process system you are unable to move the sbrk() pointer because
some application has grabbed the system memory allocation lock in some
way.
[...] The system will have issued "low on memory" warnings long before this
happens.
Huh? My (cheapo) system doesn't do that.
However for the program to be correct, you still need to handle the failure.
Exit is perfectly reasonable.


How do you know this? If the function is its own culprit, but it
strictly observes error codes, then freeing its resources and simply
returning with an error code may be sufficient to completely recover
the main program, simply with no valid result from the leaf function.

For example, if you are writing a bignum math calculator on a 32 bit
system, and an end user asks it to perform Factorial(100663296), its
likely to run out of memory in the process of trying to compute this.
If you simply free the memory used and issue some kind of error
message, it can continue with other computations without exiting
(which could be tragic, if there was a long sequence of unsaved work
for example.)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #26

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

Similar topics

7
by: Ian Roddis | last post by:
Hi all, I've written some code to make a hash data structure and associated funtions (insert, delete, search). In the delete function, I want to free() the key and the associated value. But...
4
by: Tank | last post by:
ld.so.1: internal: malloc failed I'm getting the above on a simple fopen() in a production program. I know that fopen calls malloc, but what would cause this and how do I fix it? Have I hit...
6
by: I_have_nothing | last post by:
Hi! I am new in C. I try to use dynamical allocation fuction malloc( ) and realloc( ). I found something strange. After several calling realloc( ), the malloc( ) will give me a Segmentation...
12
by: gooch | last post by:
I originally posted the following code in a group discussing threads but after further research I think I have a c question about the code. I know there are a couple of non standard c includes here...
17
by: Chen Shusheng | last post by:
Hi all, In fact, I want to let my memory run out. And see what will happen. My system is windowsXp. Memory is 256M.I think my cdes will apply more memory than I have. Codes are below: ...
6
by: sam_cit | last post by:
Hi Everyone, I wanted to know as to how malloc() works, if my understanding is correct, it is implementation specific of the vendor who provides the library(alloc.h). If so, is there any...
71
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a...
6
by: itsolution | last post by:
Hi folks, Could you shed some light on this issue? my program is running on Freebsd as a daemon. When user sends a request, it forks itself and lets its child process handles the request....
173
by: Marty James | last post by:
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....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.