home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky vmsnet.internals:1451 vmsnet.misc:935 comp.lang.c:15021
- Path: sparky!uunet!caen!uwm.edu!csd4.csd.uwm.edu!markh
- From: markh@csd4.csd.uwm.edu (Mark)
- Newsgroups: vmsnet.internals,vmsnet.misc,comp.lang.c
- Subject: Re: malloc() as a user defined function
- Date: 15 Oct 1992 15:41:34 GMT
- Organization: Computing Services Division, University of Wisconsin - Milwaukee
- Lines: 78
- Message-ID: <1bk3feINNiad@uwm.edu>
- References: <Bvv6pH.Gzy@cs.psu.edu>
- NNTP-Posting-Host: 129.89.7.4
-
- In article <Bvv6pH.Gzy@cs.psu.edu> ytang@red.crayola.cs.psu.edu (Yuan-Ling Tang) writes:
- >
- >Hi netters:
- >
- > In programming on dynamic memory allocation, I prefer doing check on
- > every malloc(). I.e.:
- >
- > if ((p=(SOME_TYPE *)malloc(sizeof(SOME_TYPE))) == NULL) {
- > printf("Malloc error.\n");
- > exit(0);
- > }
- >
- > It turned out it's a pain to type in the above four lines if I have
- > lots of malloc() invocations in the program, also, the program looks
- > ugly. So I tried to use a function called my_malloc():
-
- Well, then don't type the lines. ;)
-
- First declare dynamic pointer types like so:
-
- typedef struct Type *Type;
-
- instead of
-
- typedef struct Type Type;
-
- Second, eliminate the reference to the base type:
-
- if ((p=(Type)malloc(sizeof *p)) == NULL) {
- printf("Malloc error.\n");
- exit(0);
- }
-
- Third, rationalize the parentheses away:
-
- p = (Type)malloc(sizeof *p);
- if (p == NULL) {
- printf("Malloc error.\n");
- exit(0);
- }
-
- Fourth, if you don't like the curly brackets, then rationalize them away too:
-
- p = (Type)malloc(sizeof *p);
- if (p == NULL)
- printf("Malloc error.\n"),
- exit(0);
-
- Fifth, if you don't like the extra lines, eliminate them:
-
- p = (Type)malloc(sizeof *p);
- if (p == NULL) printf("Malloc error.\n"), exit(0);
-
- And sixth, if you don't like the extra typing, remove the NULL:
-
- p = (Type)malloc(sizeof *p);
- if (p == 0) printf("Malloc error.\n"), exit(0);
-
- There. Now how does that compare with this?
-
- > if ((p=(SOME_TYPE *)malloc(sizeof(SOME_TYPE))) == NULL) {
- > printf("Malloc error.\n");
- > exit(0);
- > }
-
- If you furthermore want your program to crash on malloc failures, then
- write a functon for this routine:
-
- void *Allocate(int Size) {
- void *X = malloc(Size);
- if (X == 0) printf("Malloc error.\n"), exit(0);
- }
-
- and use it in place of the two lines above:
-
- p = (Type)Allocate(sizeof *p);
-
- Better?
-