[lxc-devel] [PATCH lxcfs 5/5] cgfs: improve read_file and append_line

Serge Hallyn serge.hallyn at ubuntu.com
Thu Jan 7 18:49:25 UTC 2016


Quoting Wolfgang Bumiller (w.bumiller at proxmox.com):
> getline() returns the length which can be passed to
> append_line to avoid a strlen() call.
> 
> Additionally with the length already known memcpy() can be
> used instead of strcpy(). A +1 to the length will include
> the terminating null byte as it is included in getline(3)'s
> output.
> 
> Signed-off-by: Wolfgang Bumiller <w.bumiller at proxmox.com>

Acked-by: Serge E. Hallyn <serge.hallyn at ubuntu.com>

> ---
>  cgfs.c | 11 ++++++-----
>  1 file changed, 6 insertions(+), 5 deletions(-)
> 
> diff --git a/cgfs.c b/cgfs.c
> index 681a478..ec0f630 100644
> --- a/cgfs.c
> +++ b/cgfs.c
> @@ -90,11 +90,11 @@ static void dorealloc(char **mem, size_t oldlen, size_t newlen)
>  		*mem = tmp;
>  	}
>  }
> -static void append_line(char **contents, char *line, size_t *len)
> +static void append_line(char **contents, size_t *len, char *line, ssize_t linelen)
>  {
> -	size_t newlen = *len + strlen(line);
> +	size_t newlen = *len + linelen;
>  	dorealloc(contents, *len, newlen + 1);
> -	strcpy(*contents + *len, line);
> +	memcpy(*contents + *len, line, linelen+1);
>  	*len = newlen;
>  }
>  
> @@ -104,12 +104,13 @@ static char *read_file(const char *from)
>  	char *contents = NULL;
>  	FILE *f = fopen(from, "r");
>  	size_t len = 0, fulllen = 0;
> +	ssize_t linelen;
>  
>  	if (!f)
>  		return NULL;
>  
> -	while (getline(&line, &len, f) != -1) {
> -		append_line(&contents, line, &fulllen);
> +	while ((linelen = getline(&line, &len, f)) != -1) {
> +		append_line(&contents, &fulllen, line, linelen);
>  	}
>  	fclose(f);
>  
> -- 
> 2.1.4
> 
> 
> _______________________________________________
> lxc-devel mailing list
> lxc-devel at lists.linuxcontainers.org
> http://lists.linuxcontainers.org/listinfo/lxc-devel


More information about the lxc-devel mailing list