home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!spool.mu.edu!umn.edu!csus.edu!netcom.com!netcomsv!ulogic!hartman
- From: hartman@ulogic.UUCP (Richard M. Hartman)
- Newsgroups: comp.lang.c
- Subject: Re: pointer assignment problem
- Message-ID: <749@ulogic.UUCP>
- Date: 18 Dec 92 18:50:58 GMT
- References: <1992Dec13.181118.2693@seas.gwu.edu> <Bz9Gxp.DMz@netnews.jhuapl.edu>
- Distribution: usa
- Organization: negligable
- Lines: 60
-
- In article <Bz9Gxp.DMz@netnews.jhuapl.edu> bandy@netnews.jhuapl.edu (Mike Bandy) writes:
- >saud@seas.gwu.edu (Temporary account (slc 11/19/92)) writes:
- >
- >>Hi:
- >
- >>I am having problem with pointer assignment
- >
- >>look at this pleae
- >>
- >> function_node *tmp_node;
- >
- >> tmp_node = (function_node *) malloc (sizeof(tmp_node));
- >
- >Think about what tmp_node is; it's a pointer to a structure. What gets
- >malloc'ed is (probably) 4 bytes of memory. Stick a '*' in the sizeof
- >to tell it to allocate how much tmp_node _points to_ . Like:
- >
- > tmp_node = (function_node *) malloc (sizeof(*tmp_node));
-
- I tend to take the other tactic. I *never* use a variable name
- as the argument to sizeof() used in a malloc(), I always use the
- type name. e.g.:
-
- tmp_node = (function_node *) malloc(sizeof(function_node));
-
- This can even be encapsulated into a generic "give me a" macro:
-
- #define NEW(xxx) (xxx *) malloc(sizeof(xxx))
- tmp_node = NEW(function_node);
-
- I actually don't use the NEW macro, I just give it as an option.
-
- The main reason I use the type is that I always know what I
- wanted. If I use the variable we have the problem you have
- (forgetting the *) and ambiguity.
-
- ptr = malloc(sizeof(*ptr));
-
- what does that tell me?
-
- ptr = malloc(sizeof(struct employee_rec));
-
- tells me that ptr is supposed to hold employee information.
-
- Of course, so should the declaration of ptr....
-
- And, "ptr" may not be the best name....
-
- However, I think it is safest and clearest to only use types
- for malloc/sizeof statements and stay away from the implicit
- "you figure out the type and give me one" style that using
- the variable names represents.
-
-
- -Richard Hartman
- hartman@ulogic.COM
-
- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- "Who knows what evil lurks in the hearts of men?"
-
-