Unexpected indirection behavior

Hi all! I’m new to the Odin language, and though I’m mostly loving it I’m having a bit of trouble at the moment. I have an intermittent crash that I’ve managed to catch here in lldb (I’m on macOS) in my lay_out_file_browser procedure.

The root_node variable is supposed to hold the address of the first element of file_browser.directories (line 290). lldb shows that root_node points to some other memory (that seems to be owned by my program) that isn’t even of the right type.

This feels like a compiler bug, but there could easily be something I’m missing. Let me know what other info would be useful to provide to diagnose.

Okay, after an embarrassingly (gratifyingly?) small amount of further debugging, I found the issue: the directories array is dynamic, and later in this function I am calling a function that (eventually, maybe) appends to it, potentially causing it to reallocate and rendering my pointer invalid. The crashes are intermittent because valid data often remains in the old location.

You could avoid this by allocating a large upfront amount to the directory list to avoid reallocation and movement in memory:

file_browser.directories = make([dynamic]YourType, 0, 2048) // <- 2048 is your large capacity number that limits how much gets allocated into this array.

One possible way to avoid this. Make the number large enough to hold what you need. 2048 may be too much, you could probably get away with a lower number.

Also: [dynamic; 2048]YourType at the definition site in the struct as an alternative. make will allocate to the allocator specified; [dynamic; 2048] will allocate this, I think, to the same allocation strategy used for the struct.

2 Likes

The problem with pointers and dynamic arrays is explained in this excellent article:
https://zylinski.se/posts/dynamic-arrays-and-arenas/#dynamic-array-trouble

You could also try to use this container:

https://pkg.odin-lang.org/core/container/xar/

Karl suggested to set the allocator to panic allocator afterwards. See:

1 Like

Thanks for the suggestion, I didn’t know about that container.