473,698 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5064
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****@localho st.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****@localho st.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.c om/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************ *******@localho st.localdomain> ,
"H.A. Sujith" <su****@localho st.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.u k> writes:
"H.A. Sujith" <su****@localho st.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_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 #10

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

Similar topics

7
2513
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 since I want to be able to use this code, I can't discount the chance that the key or the value are static values on the stack. If this is the case, then free() will (obviously) fail. On Solaris <sys/ucontext.h> has a function stack_inbounds that...
4
5540
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 some kind of # files open limit or something? I'm running in Solaris 2.6. Barry Perot Systems
6
4775
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 fault. If I just call realloc( ) once before calling malloc( ), it is OK. Why? I am trying to read some double-typed items from infile and save them
12
3273
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 and the POSIX stuff is non standard but this is how I stumbled onto this question. #include <INTEGRITY.h> #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <signal.h>
17
2415
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: #include <stdlib.h> #include<stdio.h> #define MAX 1000000000
6
5491
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 standard as to how it should be implemented? If there is no space in the RAM, will malloc() return NULL or will it allocate a memory in a new page using virtual memory and return the
71
19103
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 problem? I cannot see why using malloc instead of new does not give the same result.
6
3366
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. And its main role is just to read a big xml file and save each object into its embedded DB(such as gdbm).
173
8103
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. OTOH, if you're allocating a gigabyte for a large array, this might fail, so you should definitely check for a NULL return.
0
8612
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9032
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...
0
8880
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...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5869
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
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3053
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
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
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.