Skip to content

Commit

Permalink
wrappers: Fix memory leak in Ruby wrapper
Browse files Browse the repository at this point in the history
Free the string returned from cmark_markdown_to_html.

Fix cmark_markdown_to_html argument types.
  • Loading branch information
nwellnhof committed Apr 12, 2024
1 parent f3692fc commit 17f1926
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions wrappers/wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,25 @@

module CMark
extend FFI::Library

class Mem < FFI::Struct
layout :calloc, :pointer,
:realloc, :pointer,
:free, callback([:pointer], :void)
end

ffi_lib ['libcmark', 'cmark']
attach_function :cmark_markdown_to_html, [:string, :int, :int], :string
attach_function :cmark_get_default_mem_allocator, [], :pointer
attach_function :cmark_markdown_to_html, [:string, :size_t, :int], :pointer
end

def markdown_to_html(s)
len = s.bytesize
CMark::cmark_markdown_to_html(s, len, 0)
cstring = CMark::cmark_markdown_to_html(s, len, 0)
result = cstring.get_string(0)
mem = CMark::cmark_get_default_mem_allocator
CMark::Mem.new(mem)[:free].call(cstring)
result
end

STDOUT.write(markdown_to_html(ARGF.read()))

0 comments on commit 17f1926

Please sign in to comment.