with a lot of compilers you cannot create an array on the stack at run time |
You most definitely CAN create an array on the stack. What you can't do is create one whose
size isn't known until runtime. The standard doesn't support it, although some compilers will allow it as an extension.
and rightfully so as stack frames are allocated at compile time |
The frames themselves are created at runtime, but size is known at compile time. A little more specifically, the compiler generates code to reserve the right amount of space on the stack for the local variables. That code runs at runtime.
but you can get around this using templates, |
No, the array template just moves the issue to the array created in the template.
I know that when allocating memory on the free store this is run time,but isn't all of our code compiled how does this code actually get executed at run time? |
The local variables are allocated on the stack at runtime also. In fact, you could say that all variables are allocated at runtime, even the global ones. Those are just allocated before main() is called.
The important things to remember are
- the stack is limited in size - typically a few megabytes vs. gigabytes in the heap. So don't allocate huge amounts of data on the stack. In pratice, that means don't allocate large arrays on the stack.
- Allocating and freeing data on the stack is much faster than on the heap. It is usually a single instruction to allocate all the space for local variables in a function. Note that I'm just talking about the time to allocate the memory, not the time to call the constructors and destructors.