diff --git a/include/zmalloc.h b/include/zmalloc.h index 76a3a7f..383f377 100644 --- a/include/zmalloc.h +++ b/include/zmalloc.h @@ -70,6 +70,7 @@ void *zcalloc(size_t size); void *zrealloc(void *ptr, size_t size); void zfree(void *ptr); char *zstrdup(const char *s); +char *zstrndup(const char *s, size_t n); size_t zmalloc_used_memory(void); void zmalloc_enable_thread_safeness(void); void zmalloc_set_oom_handler(void (*oom_handler)(size_t)); diff --git a/src/edge.c b/src/edge.c index a179f77..f50dc1e 100644 --- a/src/edge.c +++ b/src/edge.c @@ -55,7 +55,7 @@ node * r3_edge_branch(edge *e, int dl) { // the suffix edge of the leaf new_child = r3_tree_create(3); s1_len = e->pattern_len - dl; - e1 = r3_edge_create(strndup(s1, s1_len), s1_len, new_child); + e1 = r3_edge_create(zstrndup(s1, s1_len), s1_len, new_child); // Migrate the child edges to the new edge we just created. for ( int i = 0 ; i < tmp_edge_len ; i++ ) { diff --git a/src/node.c b/src/node.c index b2d339c..a9e0a76 100644 --- a/src/node.c +++ b/src/node.c @@ -306,7 +306,7 @@ node * r3_tree_matchl(const node * n, char * path, int path_len, match_entry * e if (entry && e->has_slug) { // append captured token to entry - str_array_append(entry->vars , strndup(substring_start, substring_length)); + str_array_append(entry->vars , zstrndup(substring_start, substring_length)); } if (restlen == 0 ) { return e->child && e->child->endpoint > 0 ? e->child : NULL; @@ -459,14 +459,14 @@ node * r3_tree_insert_pathl_(node *tree, char *path, int path_len, route * route // insert the first one edge, and break at "p" node * child = r3_tree_create(3); - r3_node_add_child(n, strndup(path, (int)(p - path)), child); + r3_node_add_child(n, zstrndup(path, (int)(p - path)), child); child->endpoint = 0; // and insert the rest part to the child return r3_tree_insert_pathl_(child, p, path_len - (int)(p - path), route, data); } else { node * child = r3_tree_create(3); - r3_node_add_child(n, strndup(path, path_len) , child); + r3_node_add_child(n, zstrndup(path, path_len) , child); // info("edge not found, insert one: %s\n", path); child->data = data; child->endpoint++; diff --git a/src/str.c b/src/str.c index 564c754..c83cd92 100644 --- a/src/str.c +++ b/src/str.c @@ -204,7 +204,7 @@ char *zstrdup(const char *s) { #endif #ifndef HAVE_STRNDUP -char *strndup(const char *s, int n) { +char *zstrndup(const char *s, int n) { char *out; int count = 0; while( count < n && s[count] ) diff --git a/src/zmalloc.c b/src/zmalloc.c index d0cf726..72447d8 100644 --- a/src/zmalloc.c +++ b/src/zmalloc.c @@ -215,6 +215,22 @@ char *zstrdup(const char *s) { return p; } +char * zstrndup (const char *s, size_t n) +{ + char *result; + size_t len = strlen (s); + + if (n < len) + len = n; + + result = (char *) zmalloc (len + 1); + if (!result) + return 0; + + result[len] = '\0'; + return (char *) memcpy (result, s, len); +} + size_t zmalloc_used_memory(void) { size_t um;