cmark

My personal build of CMark ✏️

Commit
7ae67bd161aa267aa540d30a6683a365f64bef3a
Parent
3d6155fe9a49e4a07379b816f9c7c2f00ae33dc4
Author
John MacFarlane <jgm@berkeley.edu>
Date

Merge pull request #140 from nwellnhof/set-cstr-fix

Fix chunk_set_cstr with suffix of current string

Diffstat

2 files changed, 11 insertions, 4 deletions

Status File Name N° Changes Insertions Deletions
Modified api_test/main.c 8 7 1
Modified src/chunk.h 7 4 3
diff --git a/api_test/main.c b/api_test/main.c
@@ -171,7 +171,13 @@ static void accessors(test_batch_runner *runner) {
   OK(runner, cmark_node_set_url(link, "URL"), "set_url");
   OK(runner, cmark_node_set_title(link, "TITLE"), "set_title");
 
-  OK(runner, cmark_node_set_literal(string, "LINK"), "set_literal string");
+  OK(runner, cmark_node_set_literal(string, "prefix-LINK"),
+     "set_literal string");
+
+  // Set literal to suffix of itself (issue #139).
+  const char *literal = cmark_node_get_literal(string);
+  OK(runner, cmark_node_set_literal(string, literal + sizeof("prefix")),
+     "set_literal suffix");
 
   char *rendered_html = cmark_render_html(doc, CMARK_OPT_DEFAULT);
   static const char expected_html[] =
diff --git a/src/chunk.h b/src/chunk.h
@@ -77,9 +77,7 @@ static CMARK_INLINE const char *cmark_chunk_to_cstr(cmark_mem *mem,
 
 static CMARK_INLINE void cmark_chunk_set_cstr(cmark_mem *mem, cmark_chunk *c,
                                               const char *str) {
-  if (c->alloc) {
-    mem->free(c->data);
-  }
+  unsigned char *old = c->alloc ? c->data : NULL;
   if (str == NULL) {
     c->len = 0;
     c->data = NULL;
@@ -90,6 +88,9 @@ static CMARK_INLINE void cmark_chunk_set_cstr(cmark_mem *mem, cmark_chunk *c,
     c->alloc = 1;
     memcpy(c->data, str, c->len + 1);
   }
+  if (old != NULL) {
+    mem->free(old);
+  }
 }
 
 static CMARK_INLINE cmark_chunk cmark_chunk_literal(const char *data) {