Newsgroups: comp.lang.c Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!caen!news.cs.indiana.edu!ux1.cso.uiuc.edu!news.iastate.edu!john From: john@iastate.edu (John Hascall) Subject: Re: Functions using malloc (style) Message-ID: <1991Jun30.150223.28773@news.iastate.edu> Sender: news@news.iastate.edu (USENET News System) Organization: Iowa State University, Ames, IA References: <2864543c.3e48@polyslo.CalPoly.EDU> <3545@unisoft.UUCP> <609@smds.UUCP> Distribution: na Date: Sun, 30 Jun 1991 15:02:23 GMT Lines: 58 rh@smds.UUCP (Richard Harter) writes: }Steven Lee writes: }> When you write a C function and it returns a pointer to some }> structure, how should the function do this? Many of the system }> functions I know create a static area that gets rewritten when }> the user makes multiple calls to it. This avoids the problem }> of allocating memory each time the function is called. }> The possible solutions I have come up with are: }> 1. Force the user to malloc his own space and then call the function. }> 2. The function mallocs space each time it is called. It is up to }> the user to free (release) the memory. }Either view may be appropriate, depending on usage. The problem is that }the function writer does not necessarily know what the users needs are. }For a bit of extra work you can accomodate both sets of needs. Make a }package out of it. [...big huge scheme...] Or, a more modest solution is something like this: #define ALLOC(type) ((type *)malloc(sizeof(type))) struct woozy * get_woozy(wp) struct woozy * wp; { if (wp == NULL) { /* no woozy from user, get one for them */ if ((wp == ALLOC(struct woozy)) == NULL) { /* can't get woozy: fprintf, exit, return NULL,... as appropriate */ } } /* ... etc ... */ return (wp); } Or, possibly: struct woozy * get_woozy(wp) struct woozy * wp; { static struct woozy our_woozy; if (wp == NULL) { /* no woozy from user, use ours */ wp = &our_woozy; } /* ... etc ... */ return (wp); } John ------------------------------------------------------------------------------- John Hascall An ill-chosen word is the fool's messenger. Project Vincent Iowa State University Computation Center john@iastate.edu Ames, IA 50011 (515) 294-9551