I have a number of numerical arrays which need to be available throughout the entire program so they need to be global unless there is a better approach. Now the contents of these arrays are not going to change in nearly all cases, there is one where the values will change but it is only 7 elements long and won’t increase or decrease in size.
I was going to add a delete at the end of the main proc for each unless there is a better approach:
delete(array)
so they are all freed when the program exits? Not sure pretty, new at this, or should I be creating a custom allocator and doing a:
free_all
We appreciate some suggestions… One question is does free_alll() without params remove everything without needing seperate deletes?
Hi,
You only need delete() if you use a data-structure, that allocates on the heap. Likely dynamic arrays
If you know that the arrays won’t change their size you don’t need dynamic arrays. Regular arrays are put on the stack by default. Stack variables can’t be free()d or delete()d, so you’d have nothing else to do. I would do this, unless your arrays are many thousands of elements long and can’t fit on the stack.
But if the heap/dynamic array is necessary:
If the elements need to be available in the entire program, you don’t need to free them. The operating system cleans it up for you after the program terminates. Explicitly freeing them just slows down the shutdown process.
With all that said, it’s good practice to free them anyway, since you would need to in any other case. You don’t need to make a brand new allocator, since you know that your arrays have the same lifetime (need to be delete()d together). I recommend simply using odins built in arena allocator
As for your free_all question: it has a default parameter: context.allocator. I assume this would free everything ever allocated with context.allocator, which would have consequences you probably don’t want.
Its also worth noting that it’s better to add a defer delete(array) line after the array initialization rather than putting it at the end of scope manually without a defer
For simple human reasons: Creation and destruction are handled in two consecutive lines, so you don’t easily forget things, especially if you change them. Also, that way you don’t easily screw up the order of destructions of dependent resources. Let’s say your struct contains pointers to other stuff, that is allocated separately → depending on your code you often first you have to delete the children, then the parent, so you need to carefully keep destructions in reverse order. Defer handles that automatically by working “first in - last out”.
That’s it, as far as I understand. It’s not rocket science, but it’s a nice creature comfort.
If you have an init proc and a shutdown proc, then defer doesn’t help you. You have to still manually make sure you destroy everything at the end and you order all of that correctly.