home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!stanford.edu!nntp.Stanford.EDU!dkeisen
- From: dkeisen@leland.Stanford.EDU (Dave Eisen)
- Subject: Re: A question about memory
- Message-ID: <1993Jan4.215507.10782@leland.Stanford.EDU>
- Sender: ?@leland.Stanford.EDU
- Organization: Sequoia Peripherals, Inc.
- References: <1993Jan4.210804.326@spartan.ac.BrockU.CA>
- Date: Mon, 4 Jan 93 21:55:07 GMT
- Lines: 45
-
- In article <1993Jan4.210804.326@spartan.ac.BrockU.CA> brad@spartan.ac.BrockU.CA (Brad Saxton) writes:
- >
- >Lets say you call an operating system function (say getpwuid) that
- >returns a pointer to a structure. At some point, the information
- >returned will no longer be needed, so we would like to return the memory
- >to the available pool. My question is HOW?
-
- There are three ways a function can return a pointer to a
- block of memory.
-
- (1) You pass in this pointer (or a related pointer) as a parameter
- to the function. strcpy uses this mechanism.
-
- (2) The function calls malloc or one of its relatives and returns
- a pointer to the space allocated. strdup uses this mechanism.
-
- (3) The function returns a pointer to a statically allocated buffer.
- This is the mechanism that getpwuid uses.
-
- Each method has its advantages and disadvantages: (1) is the most
- reliable and easy to implement, but then the code that calls the
- library function has to worry about passing in a buffer that is
- big enough; (2) is fine except the onus is then on the user of
- the function to free the memory when it is no longer being used;
- and (3) is great except for the fact that successive calls to
- the function use the same block of memory so if a user wants to
- access the data later in the program, he has to save it off.
-
- Each of the mechanisms require different steps be taken by the
- programmer using the library function. For this reason, the
- manual page that describes the function must include information
- about which mechanism is being used.
-
- In your case, with getpwuid, the function returns a pointer to
- a static buffer. It is illegal to call free with this pointer
- as its argument since this pointer was not obtained from malloc
- or its cousins. It uses a static buffer that cannot be deallocated
- in any way. But don't worry about it --- the buffer is not big
- enough to cause any problems in your program.
-
- --
- Dave Eisen Sequoia Peripherals: (415) 967-5644
- dkeisen@leland.Stanford.EDU Home: (415) 321-5154
- There's something in my library to offend everybody.
- --- Washington Coalition Against Censorship
-