godotengine / godotengine/godot
Array `get` or `pop_back` with a reference to a Node that has been free throws error on assignation
- Dominant language
- C++
- Stars
- 117k
- Forks
- 26.8k
- PR merge metrics
- PR metrics pending
Description
### Tested versions
- Reproducible in: v4.5.1.stable.official [f62fdbde1]
### System information
Ubuntu 24.04.3 LTS - Godot v4.5.1.stable.official [f62fdbde1]
### Issue description
Trying to assign to a variable the result of an `Array.get(0)` or `Array.pop_back()` when the array **has** 1 element (`Node`) that has been free (`queue_free`) throws an error.
```gdscript
node = _my_arr.get(0) # ERROR: Trying to assign invalid previously freed instance.
```
**Expectation:** I was expecting to receive either a `null` object, or one that will return `is_valid_object(...) == false`
### Steps to reproduce
Create a `Scene` with a `Node` and attach the following `Script`
```gdscript
extends Node
var _my_arr: Array[Node] = []
func _ready() -> void:
var node := Node.new()
_my_arr.append(node)
node.queue_free()
# Artificial wait to ensure 'node' is being free
await get_tree().create_timer(0.2).timeout
var arr_size: int = _my_arr.size()
print("_my_arr.size = %d" % [arr_size])
if arr_size <= 0:
return
# ERROR Line -> Trying to assign invalid previously freed instance.
node = _my_arr.get(0)
#node = _my_arr.pop_back() # also throws
if not is_instance_valid(node):
print("Instance not valid")
assert(false, "I was not supposed to reach here")
```
### Workaround
I can prevent the error if I check for valid before doing an assignation:
```gdscript
if not is_instance_valid(_my_arr.get(0)):
print("Instance not valid")
return
node = _my_arr.get(0)
```
### Minimal reproduction project (MRP)
N/A
Contributor guide
Assessment
This issue has not been assessed yet.