Skip to content

Memory Leak: C.CString result not freed after posting string to Dart port #112

Open
@Amirali-Amirifar

Description

@Amirali-Amirifar

Issue

In instances of using cgo, specially in bridge and custom packages, the C.CString function is called.

func SendStringToPort(port int64, msg string) {
var obj C.Dart_CObject
obj._type = C.Dart_CObject_kString
msg_obj := C.CString(msg) // go string -> char*s
// union type, we do a force conversion
ptr := unsafe.Pointer(&obj.value[0])
*(**C.char)(ptr) = msg_obj
ret := C.GoDart_PostCObject(C.Dart_Port_DL(port), &obj)
if !ret {
fmt.Println("ERROR: post to port ", port, " failed", msg)
}
}

as per Go documentation, CString allocates memory in heap using malloc in the hood. This memory is NOT cleaned further down the line using C.free, leading to memory leaks. These leaks can be verified using memory instrumentation tools.

Proposed fix:

Free the memory or, add documentation on if is this the case or not.

func SendStringToPort(port int64, msg string) {
	var obj C.Dart_CObject
	obj._type = C.Dart_CObject_kString
	msg_obj := C.CString(msg) // go string -> char*s
+	defer C.free(unsafe.Pointer(msg_obj))
	// union type, we do a force conversion
	ptr := unsafe.Pointer(&obj.value[0])
	*(**C.char)(ptr) = msg_obj
	ret := C.GoDart_PostCObject(C.Dart_Port_DL(port), &obj)
	if !ret {
		fmt.Println("ERROR: post to port ", port, " failed", msg)
	}
}

I am not fully sure if this is still the case in the latest versions, but is a long standing bug.
Let me know if you'd prefer me to test this in a newer release — though I'd prefer not to build the Flutter app myself due to the size of the toolchain (Dart, Flutter, Android Studio, etc.).

hiddify/hiddify-app#1436

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions