At one point in my program I have about a dozen calls to malloc. I want
to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL)
{
exit(EXIT_FAILU RE);
fprintf(stderr, "malloc failed");
}
for each individual call if there is a stylistically better way. How
would this be handled in commercial code? 14 3268
Marlene Stebbins wrote: At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed"); }
for each individual call if there is a stylistically better way. How would this be handled in commercial code?
Standard way is to write a wrapper you call in place of malloc
when you want this behavior. e.g.
void *safe_malloc(si ze_t size)
{
void *ret = malloc(size);
if (ret == NULL) {
fprintf(stderr, "malloc %u bytes failed", (unsigned)size) ;
exit(EXIT_FAILU RE);
}
return ret;
}
That also has the advantage of letting you decide what to do on
malloc(0)... No guarantee the printf will work with no memory
available either, mind you. I added the size to your printf
and put it before the exit :) The size is useful in case a programming
error causes you to try to malloc(-1) or some such.
-David
Marlene Stebbins <ma*****@mail.c om> wrote: At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed");
^^^^^^^^^^^^^
this message will never be printed
because it's after the exit() call
}
for each individual call if there is a stylistically better way. How would this be handled in commercial code?
You can use another wrapper function:
void *malloc_wrap(si ze_t size)
{
void *ret;
ret = malloc(size);
if (ret == NULL){
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAULU RE);
}
return ret;
}
--
Kornilios Kourtis
Computers are useless. They can only give you answers.
- Pablo Picasso
David REsnick wrote: Marlene Stebbins wrote:
At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed"); }
for each individual call if there is a stylistically better way. How would this be handled in commercial code?
Standard way is to write a wrapper you call in place of malloc when you want this behavior. e.g.
void *safe_malloc(si ze_t size) { void *ret = malloc(size); if (ret == NULL) { fprintf(stderr, "malloc %u bytes failed", (unsigned)size) ; exit(EXIT_FAILU RE); }
return ret; }
That also has the advantage of letting you decide what to do on malloc(0)... No guarantee the printf will work with no memory available either, mind you. I added the size to your printf and put it before the exit :) The size is useful in case a programming error causes you to try to malloc(-1) or some such.
Note: Under C89, casting to unsigned long (and using %lu) is safer, as
we do not know how wide size_t actually is. We still might have the
situation that (size_t)((unsig ned long)((size_t) -1)) != (size_t) -1.
Under C99 or with a C99 compliant standard library, use the length
modifier for size_t (z, i.e. %zu).
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.
In article <GWUAd.617669$n l.442454@pd7tw3 no>,
Marlene Stebbins <ma*****@mail.c om> wrote: At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed"); }
for each individual call if there is a stylistically better way. How would this be handled in commercial code?
If all these calls occur within the body of a single function, then
you may do:
x1 = malloc(whatever );
x2 = malloc(whatever );
...
xn = malloc(whatever );
if (!x1 || !x2 || ... || !xn) {
fprintf(stderr, "malloc failed");
exit(EXIT_FAILU RE);
}
--
Rouben Rostamian
Marlene Stebbins wrote: At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed"); }
I just noticed that I've got the exit and fprintf statements bass
ackwards. I should have had another cup of coffee before posting this.
MS
David REsnick wrote on 30/12/04 : void *safe_malloc(si ze_t size) { void *ret = malloc(size); if (ret == NULL) { fprintf(stderr, "malloc %u bytes failed", (unsigned)size) ; exit(EXIT_FAILU RE); }
return ret; }
I would amend this code this way:
/* interface (.h) */
#define safe_malloc(siz e) \
safe_malloc_ (size, __FILE__, __LINE__)
void *safe_malloc_ (size_t size, char const *file, int line);
/* implementation (.c) */
void *safe_malloc_ (size_t size, char const *file, int line)
{
void *p = malloc(size);
if (p == NULL)
{
fprintf (stderr
, "malloc %lu bytes failed at %s:%d\n"
, (unsigned long)size
, file
, line
);
exit (EXIT_FAILURE);
}
return ret;
}
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html
"C is a sharp tool"
Marlene Stebbins wrote: At one point in my program I have about a dozen calls to malloc. I want to check for malloc failure, but I don't want to write:
if((buffer_x = malloc(BUFSIZE * sizeof(*buffer_ x))) == NULL) { exit(EXIT_FAILU RE); fprintf(stderr, "malloc failed"); }
for each individual call if there is a stylistically better way. How would this be handled in commercial code?
"It depends." Here are a few patterns:
if ((buff1 = malloc(size1)) == NULL
|| (buff2 = malloc(size2)) == NULL
...
|| (buff12 = malloc(size12)) == NULL) {
die_horribly();
}
for (i = 0; i < 12; ++i) {
if ((buff[i] = malloc(size[i])) == NULL)
die_horribly();
}
/* malloc_wrapper( ) dies horribly on failure */
buff1 = malloc_wrapper( size1);
buff2 = malloc_wrapper( size2);
...
buff12 = malloc_wrapper( size12);
char *allbuffs = malloc(size1 + size2 + ... + size12);
if (allbuffs == NULL)
die_horribly();
buff1 = (Type1*)allbuff s;
buff2 = (Type2*)(allbuf fs + size1);
...
buff12 = (Type12*)(allbu ffs + size1 + size2 + ... + size11);
.... and many, many more.
There are at least two lessons in all this. First, there
are manymanymany ways to organize the handling of failures and
exceptional conditions in a program. Second, the choice of
method is usually not driven by the nature of the failure, but
by the structure of the program.
--
Eric Sosman es*****@acm-dot-org.invalid
Emmanuel Delahaye wrote: David REsnick wrote on 30/12/04 :
void *safe_malloc(si ze_t size) { void *ret = malloc(size); if (ret == NULL) { fprintf(stderr, "malloc %u bytes failed", (unsigned)size) ; exit(EXIT_FAILU RE); }
return ret; }
I would amend this code this way:
/* interface (.h) */
#define safe_malloc(siz e) \ safe_malloc_ (size, __FILE__, __LINE__)
void *safe_malloc_ (size_t size, char const *file, int line);
/* implementation (.c) */
void *safe_malloc_ (size_t size, char const *file, int line) { void *p = malloc(size);
if (p == NULL) { fprintf (stderr , "malloc %lu bytes failed at %s:%d\n" , (unsigned long)size , file , line ); exit (EXIT_FAILURE); }
ret isn't defined. He means return p, anyway. return ret; }
(supersedes <mn************ ***********@YOU RBRAnoos.fr>)
David REsnick wrote on 30/12/04 : void *safe_malloc(si ze_t size) { void *ret = malloc(size); if (ret == NULL) { fprintf(stderr, "malloc %u bytes failed", (unsigned)size) ; exit(EXIT_FAILU RE); }
return ret; }
I would amend this code this way:
/* interface (.h) */
#define safe_malloc(siz e) \
safe_malloc_ (size, __FILE__, __LINE__)
void *safe_malloc_ (size_t size, char const *file, int line);
/* implementation (.c) */
void *safe_malloc_ (size_t size, char const *file, int line)
{
void *p = malloc(size);
if (p == NULL)
{
fprintf (stderr
, "malloc %lu bytes failed at %s:%d\n"
, (unsigned long)size
, file
, line
);
exit (EXIT_FAILURE);
}
return p;
}
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html
"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Eskie |
last post by:
Lately I've seen alot of C and C++ code (not my own) which doesn't do any
checking if memory obtained by new or malloc is valid or if they return NULL
pointers.
Why does most people not care about doing this kind of error checking?
When I used to learn the language I was told always to check "if (p !=
NULL)" and return a error otherwise.
I...
|
by: WL |
last post by:
Hey, all. I'm creating an array of strings (char **argv style) on
the fly, and using realloc to create string pointers, and malloc
for the strings itself (if that makes any sense).
I'm using the construct
ptr = realloc(ptr, size);
*ptr = malloc(string_length);
strncpy(ptr, src, string_length);
to call realloc() multiple times. This should...
|
by: Bhalchandra Thatte |
last post by:
I am allocating a block of memory using malloc.
I want to use it to store a "header" structure
followed by structs in my application. How to calculate
the alignment without making any assumption
about the most restrictive type on my machine?
Thanks.
|
by: Brian Blais |
last post by:
Hello,
I saw on a couple of recent posts people saying that casting the return
value of malloc is bad, like:
d=(double *) malloc(50*sizeof(double));
why is this bad? I had always thought (perhaps mistakenly) that the
purpose of a void pointer was to cast into a legitimate date type. Is
this wrong? Why, and what is considered to be...
|
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.
--
| |
by: Tonio Cartonio |
last post by:
I have to read characters from stdin and save them in a string. The
problem is that I don't know how much characters will be read.
Francesco
--
-------------------------------------
http://www.riscossione.info/
|
by: Why Tea |
last post by:
Thanks to those who have answered my original question. I thought I
understood the answer and set out to write some code to prove my
understanding. The code was written without any error checking.
---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
|
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.
|
by: Bill Cunningham |
last post by:
My string.h headers declares two functions I have been using called
memfrob and strfry. They are encryption types functions. My man pages say
they are standard to linux c and gnu c. They sure aren't in my C books.
Interesting functions by they're OT here but this raises to me a question.
If a function returns a pointer to a void and and as...
|
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...
|
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...
| |
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. ...
|
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...
|
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...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |