Xref: utzoo comp.unix.wizards:19691 comp.lang.c:24458 Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!ateng!chip From: chip@ateng.com (Chip Salzenberg) Newsgroups: comp.unix.wizards,comp.lang.c Subject: Allocating space for path names (was Re: of course!) Message-ID: <25840931.23664@ateng.com> Date: 11 Dec 89 20:08:16 GMT References: <152@norsat.UUCP> <2586@unisoft.UUCP> <15769@bloom-beacon.MIT.EDU> <17264@rpp386.cactus.org> <4526@ski.cs.vu.nl> <17303@rpp386.cactus.org> <1051@root44.co.uk> <1989Nov22.224209.28911@athena.mit.edu> <128791@sun.Eng.Sun.COM> Followup-To: comp.lang.c Organization: A T Engineering, Tampa, FL Lines: 51 [ 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; or "The Usenet, in a very real sense, does not exist."