home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #23 / NN_1992_23.iso / spool / vmsnet / internal / 1445 < prev    next >
Encoding:
Internet Message Format  |  1992-10-13  |  1.8 KB

  1. Xref: sparky vmsnet.internals:1445 vmsnet.misc:927 comp.lang.c:14941
  2. Path: sparky!uunet!math.fu-berlin.de!news.netmbx.de!Germany.EU.net!mcsun!news.funet.fi!hydra!klaava!wirzeniu
  3. From: wirzeniu@klaava.Helsinki.FI (Lars Wirzenius)
  4. Newsgroups: vmsnet.internals,vmsnet.misc,comp.lang.c
  5. Subject: Re: malloc() as a user defined function
  6. Message-ID: <1992Oct10.122221.4794@klaava.Helsinki.FI>
  7. Date: 10 Oct 92 12:22:21 GMT
  8. References: <Bvv6pH.Gzy@cs.psu.edu>
  9. Organization: University of Helsinki
  10. Lines: 42
  11.  
  12. ytang@red.crayola.cs.psu.edu (Yuan-Ling Tang) asks about writing a
  13. wrapper around malloc to check its return value and do error recovery if
  14. the allocation fails.  His approach led to the need to write a new
  15. function for each type.
  16.  
  17. The usual way to solve this problem is probably to use the same type as
  18. malloc, that is `void *' when using Standard C, `char *' otherwise.  You
  19. then get a function similar to this one:
  20.  
  21.     #include <stdio.h>
  22.     #include <stdlib.h>
  23.  
  24.     void *my_malloc(size_t size) {
  25.         void *p;
  26.  
  27.         p = malloc(size);
  28.         if (p == NULL) {
  29.             fprintf(stderr, "can't allocate %lu bytes, "
  30.                     "aborting program.\n", 
  31.                     (unsigned long) size);
  32.             exit(EXIT_FAILURE);
  33.         }
  34.         return p;
  35.     }
  36.  
  37. (The above code is untested.  Also note that I printed the error to
  38. stderr, as is customary for error messages, and returned EXIT_FAILURE
  39. instead 0, so that the exit code of the program indicates an error. 
  40. Depending on your application, you may have to change the behaviour when
  41. malloc fails.)
  42.  
  43. The user will then use my_malloc exactly like malloc, but with no need
  44. to check the return value (if the function returns at all, the value is
  45. valid).  For example:
  46.  
  47.     struct foo *ptr1, *ptr2;
  48.  
  49.     ptr1 = my_malloc(sizeof(struct foo));
  50.     ptr2 = my_malloc(sizeof(struct foo));
  51.  
  52. --
  53. Lars.Wirzenius@helsinki.fi  (finger wirzeniu@klaava.helsinki.fi)
  54.