summaryrefslogtreecommitdiffstats
path: root/src/H5MM.c
diff options
context:
space:
mode:
authorDana Robinson <43805+derobins@users.noreply.github.com>2022-08-05 23:11:13 (GMT)
committerGitHub <noreply@github.com>2022-08-05 23:11:13 (GMT)
commitb22984600a04120088f59bb5876c9d5258fd64b7 (patch)
tree9324ab3744739b1b10b5e35a659dbe32edd51baa /src/H5MM.c
parent54f116b42db2d2aabd6fdb58cebb99f04f106310 (diff)
downloadhdf5-b22984600a04120088f59bb5876c9d5258fd64b7.zip
hdf5-b22984600a04120088f59bb5876c9d5258fd64b7.tar.gz
hdf5-b22984600a04120088f59bb5876c9d5258fd64b7.tar.bz2
Adds platform-independent basename and dirname (#1951)
* Adds platform-independent basename and dirname * Tidy up H5_dirname and H5_basename implementations and add tests * Committing clang-format changes * Fix misspelling * Several fixes for H5_dirname/H5_basename from review * Committing clang-format changes * Add reason to VERIFY_STR macros in th5_system.c * Use H5MM_free instead of HDfree in H5_dirname/H5_basename tests Co-authored-by: Jordan Henderson <jhenderson@hdfgroup.org> Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
Diffstat (limited to 'src/H5MM.c')
-rw-r--r--src/H5MM.c47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/H5MM.c b/src/H5MM.c
index 6943887..9c03ceb 100644
--- a/src/H5MM.c
+++ b/src/H5MM.c
@@ -504,6 +504,53 @@ done:
} /* end H5MM_strdup() */
/*-------------------------------------------------------------------------
+ * Function: H5MM_strndup
+ *
+ * Purpose: Duplicates a string, including memory allocation, but only
+ * copies at most `n` bytes from the string to be duplicated.
+ * If the string to be duplicated is longer than `n`, only `n`
+ * bytes are copied and a terminating null byte is added.
+ * NULL is NOT an acceptable value for the input string.
+ *
+ * If the string to be duplicated is the NULL pointer, then
+ * an error will be raised.
+ *
+ * Return: Success: Pointer to a new string
+ * Failure: NULL
+ *-------------------------------------------------------------------------
+ */
+char *
+H5MM_strndup(const char *s, size_t n)
+{
+#if defined H5_MEMORY_ALLOC_SANITY_CHECK
+ size_t len;
+#endif
+ char *ret_value = NULL;
+
+ FUNC_ENTER_NOAPI(NULL)
+
+ if (!s)
+ HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, NULL, "NULL string not allowed")
+
+#if defined H5_MEMORY_ALLOC_SANITY_CHECK
+ for (len = 0; len < n && s[len] != '\0'; len++)
+ ;
+
+ if (NULL == (ret_value = H5MM_malloc(len + 1)))
+ HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed")
+
+ H5MM_memcpy(ret_value, s, len);
+ ret_value[len] = '\0';
+#else
+ if (NULL == (ret_value = HDstrndup(s, n)))
+ HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "string duplication failed")
+#endif
+
+done:
+ FUNC_LEAVE_NOAPI(ret_value)
+} /* end H5MM_strndup() */
+
+/*-------------------------------------------------------------------------
* Function: H5MM_xfree
*
* Purpose: Just like free(3) except null pointers are allowed as