When the life of a buffer is tied to the life of a function, it makes sense to allocate it on the stack because it's much easier to pop memory off the stack then to garbage collect it later. For example if had a function that required a buffer to read from some sort of input, it would make sense to allocate the buffer on the stack, i.e.

run() {
  byte buffer[BUFF_SIZE];
  while(running) {
    int n = read(buffer, BUFF_SIZE);
    ...

However, what if I want the size of the buffer to be configurable at runtime? Maybe this function is part of some sort of library that allows the user to specify a smaller or larger buffer to optimize the number of read calls. As far as I know, in order for a library to have a buffer whose length isn't known until runtime, it would require allocating it on the heap. Then we have a buffer that is only needed for the life of this function but still needs to be garbage collected. The solution I came up with for this type of scenario is what I am calling "dynamic sized stack frames". The buffer could be allocated on the stack, and the length of the buffer could be pushed on the stack as well so the function can properly clean it when it returns. I don't know of any languages that support this type of functionality, does anyone know if there is one? Maybe this is a new feature that D could introduce in a later version?

As far as implementation there's a couple of ways this could be done...the caller could allocate the buffer, or the caller could just push the buffer length as an extra parameter and the callee could be solely responsible for allocating the buffer and cleaning it up afterwards (as I'm writing this that sounds like a safer option). Anyway I wanted to put this idea out there and see what people's thoughts are. Thanks in advance for any helpful opinions or criticism.

Reply via email to