Reputation: 349
I don't really understand when I should be allocating memory on the heap and when I should allocate on the stack. All I really know is that allocating on the stack is faster, but since the stack is smaller I shouldn't use it to allocate large data structures; what other things should I take into account when deciding where to allocate memory? Edit: where should I allocate instance variables?
Upvotes: 7
Views: 7700
Reputation: 117
In my experience heap allocation is most useful when you want to declare the size of an array of objects at runtime.
int numberOfInts;
cout << "How many integers would you like to store?: ";
cin >> numberOfInts;
int *heapArray = new int[numberOfInts];
This code will give you a pointed array of ints of size numberOfInts. It's also possible to do this in the stack, but it's considered unsafe, and you may get the error this site is named after.
Upvotes: 4
Reputation: 38785
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
int
or double
or MyClass temp1;
variablechar 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.)
Upvotes: 1
Reputation: 40769
Use the heap when the memory must persist beyond the scope of the current function.
Upvotes: 3
Reputation: 69692
Upvotes: 7