Recursively appending to dynamic array leads to segmentation fault
Consider the following:
fn contrived(arr: ^[]int, x: int): int {
i := len(arr^)
arr^ = append(arr^, 0)
if x != 0 {
arr^[i] = contrived(arr, x-1)
//val := contrived(arr, x-1)
//arr^[i] = val
}
return x + 1
}
fn main() {
arr := []int{}
contrived(&arr, 10)
printf("%v\n", arr)
}
When I run it in its current state it results in a segmentation fault, when I change the comments so that it saves the result to the val variable and then writes it it gives the expected result of [10 9 8 7 6 5 4 3 2 1 0]. When run with an initial value of 4 instead of 10 i got [0 0 1 0] but no segmentation fault.
I assume the compiled code works something like this: first, add the index to the array pointer to get the result memory address. second, evaluate the right hand side of the assignment. third, write the value to the previously calculated memory address. The problem is that if the evaluation has the side effect of causing a reallocation of the array, then the calculated address becomes a dangling pointer.
@ABlobOfGarbage You are right. Thanks for reporting!
Related: #543
Go runs this example without issue: https://go.dev/play/p/_e-LfTPGPKX