You can only use the stack as storage space when you know at compile time how big the storage you are going to need is. It follows that you can use the stack for
- Single objects (like you do declare a local
int
or double
or MyClass temp1;
variable
- statically-sized arrays (like you do when you declare
char local_buf[100];
or MyDecimal numbers[10];
You have to use the heap ("free store") when you only know how much space you need at runtime and you should probably use the heap for large statically known buffers (like don't do char large_buf[32*1024*1024];
)
Normally however, you very seldomly should touch the heap directly, but normally use objects that manage some heap memory for you (and the object possibly lives on the stack or as member of another object - where you then don't care where the other object lives)
To give some example code:
{
char locBuf[100]; // 100 character buffer on the stack
std::string s; // the object s will live on the stack
myReadLine(locBuf, 100); // copies 100 input bytes to the buffer on the stack
s = myReadLine2();
// at this point, s, the object, is living on the stack - however
// inside s there is a pointer to some heap allocated storage where it
// saved the return data from myReadLine2().
}
// <- here locBuf and s go out-of-scope, which automatically "frees" all
// memory they used. In the case of locBuf it is a noop and in the case of
// s the dtor of s will be called which in turn will release (via delete)
// the internal buffer s used.
So to give a short answer to your question when: Don't allocate anything on the heap (via new
) unless this is done via an appropriate wrapper object. (std::string, std::vector, etc.)