I’ve been programming for a while but It’s been mostly Java and C#. I’ve never actually had to manage memory on my own. I recently began programming in C++ and I’m a little confused as to when I should store things on the stack and when to store them on the heap.
My understanding is that variables which are accessed very frequently should be stored on the stack and objects, rarely used variables, and large data structures should all be stored on the heap. Is this correct or am I incorrect?
No, the difference between stack and heap isn’t performance. It’s lifespan: any local variable inside a function (anything you do not malloc() or new) lives on the stack. It goes away when you return from the function. If you want something to live longer than the function that declared it, you must allocate it on the heap.
For a clearer understanding of what the stack is, come at it from the other end — rather than try to understand what the stack does in terms of a high level language, look up ‘call stack’ and ‘calling convention’ and see what the machine really does when you call a function. Computer memory is just a series of addresses; ‘heap’ and ‘stack’ are inventions of the compiler.