Skip to content

Commit 6a1e68a

Browse files
[C#] Fixes mem leak on string pointer (#1389)
* + fixes: #1377 * + free only when the string is valid * + free when ptr != 0 * use the "list" way to free a ptr * + free when size > 0 * + free ptr for cases: ListCanonLift and ListLift
1 parent ca9a3b5 commit 6a1e68a

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

crates/csharp/src/function.rs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,10 @@ impl Bindgen for FunctionBindgen<'_, '_> {
788788
"
789789
var {array} = new {ty}[{length}];
790790
new global::System.Span<{ty}>((void*)({address}), {length}).CopyTo(new global::System.Span<{ty}>({array}));
791+
792+
if ({length} > 0) {{
793+
global::System.Runtime.InteropServices.NativeMemory.Free((void*){address});
794+
}}
791795
"
792796
);
793797

@@ -838,10 +842,26 @@ impl Bindgen for FunctionBindgen<'_, '_> {
838842
}
839843

840844
Instruction::StringLift { .. } => {
841-
results.push(format!(
845+
let str = self.locals.tmp("str");
846+
let op0 = &operands[0];
847+
let op1 = &operands[1];
848+
849+
let get_str = format!(
842850
"global::System.Text.Encoding.UTF8.GetString((byte*){}, {})",
843-
operands[0], operands[1]
844-
));
851+
op0, op1
852+
);
853+
854+
uwriteln!(
855+
self.src,
856+
"
857+
var {str} = {get_str};
858+
if ({op1} > 0) {{
859+
global::System.Runtime.InteropServices.NativeMemory.Free((void*){op0});
860+
}}
861+
"
862+
);
863+
864+
results.push(str);
845865
}
846866

847867
Instruction::ListLower { element, realloc } => {
@@ -941,6 +961,10 @@ impl Bindgen for FunctionBindgen<'_, '_> {
941961
{body}
942962
{array}.Add({result});
943963
}}
964+
965+
if ({length} > 0) {{
966+
global::System.Runtime.InteropServices.NativeMemory.Free((void*){address});
967+
}}
944968
"
945969
);
946970

0 commit comments

Comments
 (0)