Managing memory for strings...Build my own GC or what?

Is there a best practice (or any good ideas) about how to manage memory for strings? Let’s say I need to split, join, upper/lowercase, strip, search etc. In python I would just string a sequence of function/method calls together and use whatever came out the end. But many strings package functions in Odin will allocate memory which I would need to free, and I guess I need to carefully read the documentation for each call to determine if they allocate or alias. This is doable but error-prone. Do people perhaps use a special allocator and put all strings into a separate block and just free that whole block at the end or something else? I mean, it borders on building your own garbage collector but maybe that is what I should do? Or something else?

Thanks and sorry for being a total noob at Odin (not programming) :slight_smile:
– Henrik

A common pattern is to do all intermediate string manipulation with the context.temp_allocator (and remembering to free_all on the allocator occasionally).

The “separate block” you mentioned sounds awfully like an Arena, if you’re not familiar with the concept: it’s a good way to allocate memory for sets of lifetimes.

Do you have a better idea of what it is you’re trying to do with strings? Ultimately, managing memory for strings is no different than anything else.

2 Likes

OK, thanks for this! Any clue on how the temporary allocator handles multiple threads? Is there one temp allocator per thread? Otherwise I guess it’s hard to know when it’s safe to call free_all.

Threads are given a new context, unless specified by the user in init_context. By default, both allocators are thread-safe.

Yes.

Awesome! Context allocators are a new way of thinking and I think they are brilliant, but they take some time to get used to. Perhaps the documentation should include some best practices and/or examples of real world problems that it solves. That could promote Odin even more, perhaps.
Thanks!

Odin could benefit from a lot more documentation, for sure, but making documentation is a lot of work so I understand it is slow going. Thankfully, Odin source code is very easy to read so most of the time when I am wondering about some implementation details, I find it easier to just read the code than to try to figure out the documentation. There’s also a bunch of example code in the GitHub - odin-lang/examples: Examples of idiomatic Odin code repo.

3 Likes

@suncore

Check out the fmt core library, e.g., package fmt - pkg.odin-lang.org. The way I would use this is to build my required string using tprintf (it will return the assembled string) and it uses the temp allocator by default, which in my game I would call free_all() on each frame if I only needed the string for that frame. For longer lived strings you just allocate and deallocate as usual, you can use something like package fmt - pkg.odin-lang.org.