Skip to content

Commit 5d9976b

Browse files
authored
Merge pull request #320 from jhawthorn/c-api-stable-memory-leaks
[0.x] Fix memory leaks of string buffers
2 parents db8cd37 + b0df48c commit 5d9976b

File tree

2 files changed

+9
-10
lines changed

2 files changed

+9
-10
lines changed

ext/commonmarker/commonmarker.c

+8-9
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,10 @@ static VALUE encode_utf8_string(const char *c_string) {
4545
return string;
4646
}
4747

48-
/* Encode a C string using the encoding from Ruby string +source+. */
49-
static VALUE encode_source_string(const char *c_string, VALUE source) {
50-
VALUE string = rb_str_new2(c_string);
51-
rb_enc_copy(string, source);
52-
return string;
48+
static VALUE commonmarker_cstr_adopt(const char *str, rb_encoding *enc) {
49+
VALUE ret = rb_enc_str_new_cstr(str, enc);
50+
cmark_get_default_mem_allocator()->free(str);
51+
return ret;
5352
}
5453

5554
static void rb_mark_c_struct(void *data) {
@@ -175,7 +174,7 @@ static VALUE rb_markdown_to_html(VALUE self, VALUE rb_text, VALUE rb_options, VA
175174
cmark_parser_free(parser);
176175
cmark_node_free(doc);
177176

178-
return rb_utf8_str_new_cstr(html);
177+
return commonmarker_cstr_adopt(html, rb_utf8_encoding());
179178
}
180179

181180
/*
@@ -204,7 +203,7 @@ static VALUE rb_markdown_to_xml(VALUE self, VALUE rb_text, VALUE rb_options, VAL
204203
cmark_parser_free(parser);
205204
cmark_node_free(doc);
206205

207-
return rb_utf8_str_new_cstr(xml);
206+
return commonmarker_cstr_adopt(xml, rb_utf8_encoding());
208207
}
209208

210209
/*
@@ -1178,7 +1177,7 @@ static VALUE rb_html_escape_href(VALUE self, VALUE rb_text) {
11781177
if (houdini_escape_href(&buf, (const uint8_t *)RSTRING_PTR(rb_text),
11791178
RSTRING_LEN(rb_text))) {
11801179
result = (char *)cmark_strbuf_detach(&buf);
1181-
return encode_source_string(result, rb_text);
1180+
return commonmarker_cstr_adopt(result, rb_enc_get(rb_text));
11821181

11831182
}
11841183

@@ -1199,7 +1198,7 @@ static VALUE rb_html_escape_html(VALUE self, VALUE rb_text) {
11991198
if (houdini_escape_html0(&buf, (const uint8_t *)RSTRING_PTR(rb_text),
12001199
RSTRING_LEN(rb_text), 0)) {
12011200
result = (char *)cmark_strbuf_detach(&buf);
1202-
return encode_source_string(result, rb_text);
1201+
return commonmarker_cstr_adopt(result, rb_enc_get(rb_text));
12031202
}
12041203

12051204
return rb_text;

lib/commonmarker/version.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# frozen_string_literal: true
22

33
module CommonMarker
4-
VERSION = "0.23.10"
4+
VERSION = "0.23.11"
55
end

0 commit comments

Comments
 (0)