aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSahana Prasad <sahana@redhat.com>2020-01-10 15:03:43 +0100
committerAndreas Schneider <asn@cryptomilk.org>2020-01-23 09:19:07 +0100
commit240bf3236a15f2bfb2d3013635588cae1836057b (patch)
treeb7c51554b5ca19bb0e00ee73977f9aee6b3ebbca
parent844f92efea2f42f4cddee28cb9142e48edc45359 (diff)
downloadlibssh-240bf3236a15f2bfb2d3013635588cae1836057b.tar.gz
libssh-240bf3236a15f2bfb2d3013635588cae1836057b.tar.xz
libssh-240bf3236a15f2bfb2d3013635588cae1836057b.zip
misc: Simplifies ssh_strreplace().
Signed-off-by: Sahana Prasad <sahana@redhat.com> Reviewed-by: Andreas Schneider <asn@cryptomilk.org> Reviewed-by: Jakub Jelen <jjelen@redhat.com>
-rw-r--r--src/misc.c27
1 files changed, 14 insertions, 13 deletions
diff --git a/src/misc.c b/src/misc.c
index affb3eb4..52ca3a47 100644
--- a/src/misc.c
+++ b/src/misc.c
@@ -1797,29 +1797,29 @@ err:
* @param[in] replace String to be replaced is stored in replace.
*
* @returns src_replaced a pointer that points to the replaced string.
- * NULL if allocation fails.
+ * NULL if allocation fails or if src is NULL.
*/
char *ssh_strreplace(char *src, const char *pattern, const char *replace)
{
char *p = NULL;
char *src_replaced = NULL;
- size_t len_replaced;
+
+ if (src == NULL) {
+ return NULL;
+ }
if (pattern == NULL || replace == NULL) {
- return src;
+ return strdup(src);
}
- if ((p = strstr(src, pattern)) != NULL) {
+ p = strstr(src, pattern);
+
+ if (p != NULL) {
size_t offset = p - src;
- size_t len = strlen(src);
size_t pattern_len = strlen(pattern);
size_t replace_len = strlen(replace);
-
- if (replace_len != pattern_len) {
- len_replaced = strlen(src) + replace_len - pattern_len + 1;
- } else {
- len_replaced = strlen(src) + 1;
- }
+ size_t len = strlen(src);
+ size_t len_replaced = len + replace_len - pattern_len + 1;
src_replaced = (char *)malloc(len_replaced);
@@ -1831,9 +1831,10 @@ char *ssh_strreplace(char *src, const char *pattern, const char *replace)
memcpy(src_replaced, src, offset);
memcpy(src_replaced + offset, replace, replace_len);
memcpy(src_replaced + offset + replace_len, src + offset + pattern_len, len - offset - pattern_len);
+ return src_replaced; /* free in the caller */
+ } else {
+ return strdup(src);
}
-
- return src_replaced; /* free in the caller */
}
/** @} */