c3lang / c3-web

The website for C3 made with Astro!
https://c3-lang.org/
MIT License
43 stars 21 forks source link

Write a page on memory management, allocator scopes, for temporary allocator and arenas #58

Open joshring opened 2 weeks ago

joshring commented 2 weeks ago

We could do with a dedicated section on memory allocation, including allocator scopes, how to use the temporary allocator for which automatically frees

Expanding this content of this into a section like defer etc

include

tomaskallup commented 2 weeks ago

My initial thoughts on this are to have multiple sections:

Allocators

Section describing all the current allocators with an example of how to acquire it and brief info of how it works.

Using allocators

This should describe how to actually use an allocators once you have it. @pool and its friends, probably even how to supply the allocator to a std initializer (for example to allocate a List or something like that)

Memory allocation & freeing

This should maybe be first and should expand on the section you linked, mainly describing how you can allocate a piece of memory the C way (not caring about allocators, just using the default heap) and how to free it afterwards. This may sound simple to some, but will probably help most people get started with the basics. Ideally this should also demonstrate how to use defer & try defer (or catch defer? Not sure what it's called) to free the allocated memory in some simple examples.

Also thinking about this, there should maybe be a small sub-section showing how to free stuff you get from std (DString, List, ...).

joshring commented 2 weeks ago

I think with defer it's helpful but could be distracting, we should try and show the non-defer option then introduce the defer option with a link to that section then we can "take people with us" through that jump.

Seems like a good set of ideas :+1: so far, I am currently on step 0, getting some more understanding of them at the moment (which will probably shape the content quite a bit based on what I found hard!)

joshring commented 2 weeks ago

today I learned: using an arena outside of a @scoped block

module test;
import std::io;

fn void main()
{

    DynamicArenaAllocator dynamic_arena;
    dynamic_arena.init(4096, allocator::heap());

    double *f = allocator::alloc(&dynamic_arena, double);
    io::printfn("is this valid memory? %s", *f);

    // TODO test out
    /// double f[] = allocator::alloc_array(&dynamic_arena, double, 100);

    // Release any dynamic arena memory.
    dynamic_arena.free();
}

also worth mentioning that you can do this globally inside main, then any nested function has the default allocator changed