[PATCH] Avoid some memory waste while allocating tcbtab.

Dmitry V. Levin ldv at altlinux.org
Mon Feb 29 23:27:09 UTC 2016


On Wed, Feb 24, 2016 at 02:22:34PM +0100, Nahim El Atmani wrote:
[...]
> --- a/strace.c
> +++ b/strace.c
> @@ -689,6 +689,18 @@ newoutf(struct tcb *tcp)
>  }
>  
>  static void
> +create_tcbtab(void)
> +{
> +	struct tcb *tcp;
> +
> +	/* Allocate the initial tcbtab.  */
> +	tcbtabsize = 1; /* We don't need much more at first */
> +	tcbtab = xcalloc(tcbtabsize, sizeof(tcbtab[0]));
> +	tcp = xcalloc(tcbtabsize, sizeof(*tcp));
> +	tcbtab[0] = tcp;
> +}
> +
> +static void
>  expand_tcbtab(void)
>  {
>  	/* Allocate some more TCBs and expand the table.
> @@ -696,14 +708,22 @@ expand_tcbtab(void)
>  	   callers have pointers and it would be a pain.
>  	   So tcbtab is a table of pointers.  Since we never
>  	   free the TCBs, we allocate a single chunk of many.  */
> -	unsigned int i = tcbtabsize;
> -	struct tcb *newtcbs = xcalloc(tcbtabsize, sizeof(newtcbs[0]));
> -	struct tcb **newtab = xreallocarray(tcbtab, tcbtabsize * 2,
> -					    sizeof(tcbtab[0]));
> -	tcbtabsize *= 2;
> -	tcbtab = newtab;
> -	while (i < tcbtabsize)
> -		tcbtab[i++] = newtcbs++;
> +	unsigned int i;
> +	struct tcb *newtcbs;
> +	struct tcb **newtab;
> +
> +	if (!tcbtabsize) {
> +		create_tcbtab();
> +	} else {
> +		i = tcbtabsize;
> +		newtcbs = xcalloc(tcbtabsize, sizeof(newtcbs[0]));
> +		newtab = xreallocarray(tcbtab, tcbtabsize * 2,
> +				       sizeof(tcbtab[0]));
> +		tcbtabsize *= 2;
> +		tcbtab = newtab;
> +		while (i < tcbtabsize)
> +			tcbtab[i++] = newtcbs++;
> +	}
>  }

This is better.  Do you think create_tcbtab that's called just once
from expand_tcbtab worth to be a separate function?

What if these two branches of code were merged, e.g.

	unsigned int new_tcbtabsize, alloc_tcbtabsize;
	if (tcbtabsize) {
		 alloc_tcbtabsize = tcbtabsize;
		 new_tcbtabsize = tcbtabsize << 1;
	} else {
		alloc_tcbtabsize = new_tcbtabsize = 1;
	}
	etc.

Wouldn't the result code be more compact and somewhat more readable?


-- 
ldv
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 819 bytes
Desc: not available
URL: <http://lists.strace.io/pipermail/strace-devel/attachments/20160301/c2cc5881/attachment.bin>


More information about the Strace-devel mailing list