[PATCH v3 2/5] Introduce xstrndup function

Dmitry V. Levin ldv at altlinux.org
Tue Jun 13 21:35:11 UTC 2017


On Tue, Jun 13, 2017 at 05:26:42PM +0900, Masatake YAMATO wrote:
> * defs.h (xstrndup): New prototypes.

prototypeS? :)

> * xmalloc.c (xstrndup): New function.
> 
> Signed-off-by: Masatake YAMATO <yamato at redhat.com>
> ---
>  defs.h    |  1 +
>  xmalloc.c | 12 ++++++++++++
>  2 files changed, 13 insertions(+)
> 
> diff --git a/defs.h b/defs.h
> index 52f40b3..063394e 100644
> --- a/defs.h
> +++ b/defs.h
> @@ -398,6 +398,7 @@ void *xcalloc(size_t nmemb, size_t size)
>  void *xreallocarray(void *ptr, size_t nmemb, size_t size)
>  	ATTRIBUTE_ALLOC_SIZE((2, 3));
>  char *xstrdup(const char *str) ATTRIBUTE_MALLOC;
> +char *xstrndup(const char *str, size_t n) ATTRIBUTE_MALLOC;
>  
>  extern int read_int_from_file(const char *, int *);
>  
> diff --git a/xmalloc.c b/xmalloc.c
> index 1158927..c1ff3f5 100644
> --- a/xmalloc.c
> +++ b/xmalloc.c
> @@ -85,3 +85,15 @@ char *xstrdup(const char *str)
>  
>  	return p;
>  }
> +
> +char *xstrndup(const char *str, size_t n)
> +{
> +	char *p = xmalloc(n + 1);
> +
> +	if (!p)
> +		die_out_of_memory();
> +
> +	strncpy(p, str, n);
> +	p[n] = '\0';
> +	return p;
> +}

I think xstrndup should use strndup if the latter is available.


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


More information about the Strace-devel mailing list