GDExtension memory leak when using Array

Godot Version

4.2.1

Question

In GDExtension, when I use this code, I got a leak on static memory. How do I fix it?

These codes caused memory leak:

Array arr = Array();
arr.append(Array());
Array arr2 = arr[0];

But these codes didn’t:

Array arr = Array();
arr.append(Array());

How are you certain it’s a leak? What I see is two array variables in one code and one array variable the other.

I assume that extra memory is that second arr2 object itself. Have you tired

Array arr = Array();
arr.append(Array());
Array arr2 = null

Does the same thing happen?

If you put your code in a for loop does the memory keep going up?

If arr2 is like this, it worked fine: Array arr2;

Here is the full function:

void Test::Test(){
    Array arr = Array();
    arr.append(Array());
    Array arr2 = arr[0]; 
}

In gdscript I do this:

func _process(delta):
	if Input.is_action_pressed("ui_accept"):
		for i in range(100):
			GDextensionClass.test()

When I hold Space, the memory goes up and never go back down.

I think it’s related to this issue: Accessing Dictionary from inside of Array results in a memory leak · Issue #1240 · godotengine/godot-cpp · GitHub

I also found this

https://www.reddit.com/r/godot/comments/mvi068/c_garbage_collector_question/

It seems like at least for C# Godot users that the Garbage collector doesn’t like to work with ref counted memory.

Which made me think, is it possible to turn off garbage collection mechanism to allow Godot’s native code to handle memory management?

I don’t use C# but have you explored this idea?

I switched the godot-cpp to the one that fixed the problem. It worked!
Here it is: Avoid creating most objects that Godot is going to use placement new to initialize (mark 2) by dsnopek · Pull Request #1379 · godotengine/godot-cpp · GitHub
It’s related to the previous link I gave.

I guess that’s it for this issue.

Thanks for helping.