Subject: Re: [PATCH 7/7] Avoid duplicating memory, and use xmemdupz instead of xstrdup.

From: Pierre Habouzit <[email-masked]>
Date: Fri, 21 Sep 2007 00:05:06 +0200

On mer, sep 19, 2007 at 10:42:16 +0000, Pierre Habouzit wrote:
> Signed-off-by: Pierre Habouzit <[email-masked]>
> ---
>  walker.c |   23 +++++++++--------------
>  1 files changed, 9 insertions(+), 14 deletions(-)
> 
> diff --git a/walker.c b/walker.c
> index 397b80d..0abdd64 100644
> --- a/walker.c
> +++ b/walker.c
> @@ -213,24 +213,19 @@ int walker_targets_stdin(char ***target, const char ***write_ref)
>  	struct strbuf buf;
>  	*target = NULL; *write_ref = NULL;
>  	strbuf_init(&buf, 0);
> -	while (1) {
> -		char *rf_one = NULL;
> -		char *tg_one;
> -
> -		if (strbuf_getline(&buf, stdin, '\n') == EOF)
> -			break;
> -		tg_one = buf.buf;
> -		rf_one = strchr(tg_one, '\t');
> -		if (rf_one)
> -			*rf_one++ = 0;
> +	while (strbuf_getline(&buf, stdin, '\n') != EOF) {
> +		char *rf_one = memchr(buf.buf, '\t', buf.len);
>  
>  		if (targets >= targets_alloc) {
> -			targets_alloc = targets_alloc ? targets_alloc * 2 : 64;
> -			*target = xrealloc(*target, targets_alloc * sizeof(**target));
> +			ALLOC_GROW(target, targets, targets_alloc);
>  			*write_ref = xrealloc(*write_ref, targets_alloc * sizeof(**write_ref));
>  		}
> -		(*target)[targets] = xstrdup(tg_one);
> -		(*write_ref)[targets] = rf_one ? xstrdup(rf_one) : NULL;
> +		if (rf_one) {
> +			(*write_ref)[targets] = xmemdupz(rf_one, buf.len - (rf_one - buf.buf));
> +		} else {

  As someone pointed to me off-list the above should be:
  +		if (rf_one) {
  +			(*write_ref)[targets] = xmemdupz(rf_one + 1, buf.len - (rf_one + 1 - buf.buf));
  +		} else {

  Or better:
  +		if (rf_one) {
  +			rf_one++; /* skip \t */
  +			(*write_ref)[targets] = xmemdupz(rf_one, buf.buf + buf.len - rf_one);
  +		} else {

  Which is definitely more readable.
-- 
·O·  Pierre Habouzit
··O                                                [email-masked]
OOO                                                http://www.madism.org