I see a lot of Forth code just doing s" Hello " s" world" s+ like it's nothing, but now that I think about it, this actually allocates 3 pointers, and lose two of them to the great nothingness. Same problem goes with most uses of slurp-file.
But if I need to put every single string address I allocate into a temporary location to free them later, like s" foo" over >r ( ... do something ... ) r> free, I'm gonna lose my mind. What is the best practice on this?
I don't see a lot of Forth code around taking memory allocation into account, and the stack aspect of it seems to go in a kind of "fire and forget" mood.
The practical
I'm working on a web server which serves HTML files, and while the request is saved in a reusable pad, the response, on the other hand, is a mix of slurped files and string concatenations.
Which means if I let the server run over the internet for some time, and let the various soup of robots you find there play with it, I might lose a consequent amount of memory just to answer them to go away.
The question
So I'm turning to the vivid Forth community around here to ask you for the best practice.
Should I:
- Run after every memory allocation in my program and check that I free them sometime
- Let the program run and restart it once a limit has been reached
- Use the gforth garbage collector extension
- Prepare a big lot of memory dedicated to a request and free everything at once at the end of the response
(1) is a scenario in my worst nightmares
(2) is the lazy way, but not that bad
(3) I looked at the code and it seems overkill for me
(4) is what I'd really like to go for, but is a bit ambitious
Bonus: What I'd do if I had to implement solution (4)
- I would allocate a big chunk of memory and save the pointer in a variable.
- Then have an equivalent of the
hereword to point at the next free location in it. - Then write new versions for
s+and other string manipulation words that just gethereand increment it by their size - At the end of the server answer, I would free the initial pointer.
Is this a good strategy? Am I missing something?