home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky vmsnet.internals:1445 vmsnet.misc:927 comp.lang.c:14941
- Path: sparky!uunet!math.fu-berlin.de!news.netmbx.de!Germany.EU.net!mcsun!news.funet.fi!hydra!klaava!wirzeniu
- From: wirzeniu@klaava.Helsinki.FI (Lars Wirzenius)
- Newsgroups: vmsnet.internals,vmsnet.misc,comp.lang.c
- Subject: Re: malloc() as a user defined function
- Message-ID: <1992Oct10.122221.4794@klaava.Helsinki.FI>
- Date: 10 Oct 92 12:22:21 GMT
- References: <Bvv6pH.Gzy@cs.psu.edu>
- Organization: University of Helsinki
- Lines: 42
-
- ytang@red.crayola.cs.psu.edu (Yuan-Ling Tang) asks about writing a
- wrapper around malloc to check its return value and do error recovery if
- the allocation fails. His approach led to the need to write a new
- function for each type.
-
- The usual way to solve this problem is probably to use the same type as
- malloc, that is `void *' when using Standard C, `char *' otherwise. You
- then get a function similar to this one:
-
- #include <stdio.h>
- #include <stdlib.h>
-
- void *my_malloc(size_t size) {
- void *p;
-
- p = malloc(size);
- if (p == NULL) {
- fprintf(stderr, "can't allocate %lu bytes, "
- "aborting program.\n",
- (unsigned long) size);
- exit(EXIT_FAILURE);
- }
- return p;
- }
-
- (The above code is untested. Also note that I printed the error to
- stderr, as is customary for error messages, and returned EXIT_FAILURE
- instead 0, so that the exit code of the program indicates an error.
- Depending on your application, you may have to change the behaviour when
- malloc fails.)
-
- The user will then use my_malloc exactly like malloc, but with no need
- to check the return value (if the function returns at all, the value is
- valid). For example:
-
- struct foo *ptr1, *ptr2;
-
- ptr1 = my_malloc(sizeof(struct foo));
- ptr2 = my_malloc(sizeof(struct foo));
-
- --
- Lars.Wirzenius@helsinki.fi (finger wirzeniu@klaava.helsinki.fi)
-