Functions using malloc (style)
John Hascall
john at iastate.edu
Mon Jul 1 01:02:23 AEST 1991
rh at 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 at iastate.edu
Ames, IA 50011 (515) 294-9551
More information about the Comp.lang.c
mailing list