From ad9e9d5dbd79f996eddaed9b9860b7e6e2d4c845 Mon Sep 17 00:00:00 2001 From: Steffen Jaeckel Date: Tue, 6 Jul 2021 10:23:28 +0200 Subject: [PATCH] add xmpp_strndup() Signed-off-by: Steffen Jaeckel --- src/common.h | 1 + src/util.c | 32 ++++++++++++++++++++++++++------ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/common.h b/src/common.h index 01a6c8f..bf018d4 100644 --- a/src/common.h +++ b/src/common.h @@ -90,6 +90,7 @@ struct _xmpp_ctx_t { void *xmpp_alloc(const xmpp_ctx_t *ctx, size_t size); void *xmpp_realloc(const xmpp_ctx_t *ctx, void *p, size_t size); char *xmpp_strdup(const xmpp_ctx_t *ctx, const char *s); +char *xmpp_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len); void xmpp_log(const xmpp_ctx_t *ctx, const xmpp_log_level_t level, diff --git a/src/util.c b/src/util.c index c9394df..db2eb8f 100644 --- a/src/util.c +++ b/src/util.c @@ -36,21 +36,41 @@ * @param ctx a Strophe context object * @param s a string * - * @return a new allocates string with the same data as s or NULL on error + * @return a newly allocated string with the same data as s or NULL on error */ char *xmpp_strdup(const xmpp_ctx_t *ctx, const char *s) { - size_t len; - char *copy; + return xmpp_strndup(ctx, s, SIZE_MAX); +} - len = strlen(s); - copy = xmpp_alloc(ctx, len + 1); +/** Duplicate a string with a maximum length. + * This function replaces the standard strndup library call with a version + * that uses the Strophe context object's allocator. + * + * @param ctx a Strophe context object + * @param s a string + * @param len the maximum length of the string to copy + * + * @return a newly allocated string that contains at most `len` symbols + * of the original string or NULL on error + */ +char *xmpp_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len) +{ + char *copy; + size_t l; + + l = strlen(s); + if (l > len) + l = len; + + copy = xmpp_alloc(ctx, l + 1); if (!copy) { xmpp_error(ctx, "xmpp", "failed to allocate required memory"); return NULL; } - memcpy(copy, s, len + 1); + memcpy(copy, s, l); + copy[l] = '\0'; return copy; }