[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: New versions of openbsd_{basename,dirname}.c



Svante Signell, le Tue 17 Jan 2012 10:52:47 +0100, a écrit :
> 	len = strlen(path);
> 	bname = malloc(len+1);
> 
> 	/* Strip trailing slashes */
> 	endp = path + len - 1;
> 	while (endp > path && *endp == '/')
> 		endp--;
> 
> 	/* All slashes becomes "/" */
> 	if (endp == path && *endp == '/') {
> 		(void)strcpy(bname, "/");

It'd probably be better to just strdup "/" here, and thus move the
malloc above just...

> 		return(bname);
> 	}
> 
> 	/* Find the start of the base */
> 	startp = endp;
> 	while (startp > path && *(startp - 1) != '/')
> 		startp--;

... here, with the exact needed size.

> 	(void)strncpy(bname, startp, endp - startp + 1);
> 	bname[endp - startp + 1] = '\0';
> 	return(bname);
> }


Same here: better move the malloc here, with the exact needed size.

> 	(void)strncpy(bname, path, endp - path + 1);
> 	bname[endp - path + 1] = '\0';
> 	return(bname);
> }

In addition to that, it might be better for performance to rather
remember how much memory was previously allocated, and only reallocate
if more memory is needed, and twice as much, so as to reduce the amount
of free/malloc calls.

Samuel


Reply to: