[comp.lang.c] Allocating space for path names

chip@ateng.com (Chip Salzenberg) (12/12/89)

[ Followups to comp.lang.c, since this is a language issue. ]

According to lm@snafu.Sun.COM (Larry McVoy):
>isadir(char *path)
>{
>	char	*dir;
>
>	dir = malloc(pathconf(path, _PC_PATH_MAX));
>
>	/* etc */
>}

That's fine, if we assume a free() call at the end.  However, a related
point is that repeated malloc/free calls can result in worse problems (due
to fragmentation) than a single unfreed malloc would have caused.  Further,
a locally malloc'd string must be freed at every possible exit point from
the routine.  Therefore, I often do something like this:

	isadir(char *path)
	{
	    static int dirsz = 0;
	    static char *dir = NULL;
	    int n;

	    n = strlen(path) + 10;  /* or whatever */
	    if (dirsz < n)
	    {
		char    *p;

		n += 20;    /* fudge factor */
		p = (dir) ? realloc(dir, n) : malloc(n);
		if (!p)
		    die_horribly();
		dirsz = n;
		dir = p;
	    }

	    /* stuff */
	}

The static string doesn't get repeatedly allocated and freed.  And I need
not worry about freeing it before returning.

Of course, this idiom gets pretty verbose.  It sometimes is worth defining a
structure containing the pointer and length, and putting the whole
malloc/realloc jazz in a common subroutine.  Also, if several routines do
something similar, you might want to have them share a common buffer.
-- 
You may redistribute this article only to those who may freely do likewise.
Chip Salzenberg at A T Engineering;  <chip@ateng.com> or <uunet!ateng!chip>
	  "The Usenet, in a very real sense, does not exist."