Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting. Golang _runtime_ requires malloc, so even if used carefully I doubt you could use go in this way.


But, malloc doesn't have to be significantly advanced. In a situation where you have a large chunk of memory unallocated, the simplest thing to do is just to "bump" allocate it. Freeing it is a bit of pain of course, but you could build a freelist out of the chunks that are free.

So, the suggestion looks like this:

    struct freemem {
      int len;
      char *addr;
      struct freemem *next; 
    };
    // globals
    int total_mem_size;
    char *start_of_memory;
    char *bump_pointer;
    struct freemem *freelist;
Allocate is simply:

    if bump_pointer + MIN(size_to_allocate, sizeof(struct freemem)) < total_mem_size:
      int *b = (int *) bump_pointer;
      *b = MIN(size_to_allocate, sizeof(struct freemem);
      return b + sizeof(int)
    else
      iterate over freelist, checking for size_to_allocate < freelist->len
      return freelist->addr (the *b business is already taken care of)
Deallocate simply turns the discarded memory into a struct freemem and prepends it to the freelist, setting addr = the discarded address, and len = *(addr - sizeof(int)) (it's for this reason that we allocate a minimum size of sizeof(struct freemem))

That's a basic malloc / free.


> Freeing it is a bit of pain of course, but you could build a freelist out of the chunks that are free.

If you want a much longer explanation of this technique, I wrote a chapter about object pools[1] that discusses exactly this[2].

    [1] http://gameprogrammingpatterns.com/object-pool.html
    [2] http://gameprogrammingpatterns.com/object-pool.html#faster-particle-creation


Urr.. That should have been MAX, not MIN.


That's one of the main reasons we say Rust and Go aren't in the same space (and that is not a knock against Go, their choices made a lot of sense for their domain).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: