0

I'm just learning about dynamic memory allocation, but there is one thing i'd like to be explained.

One use for dynamic allocation is for dynamic sized arrays, and thats clear to me. Another use is for normal objects.

What is a situation one should use it? Is it because normally objects are pushed on the stack, and could be popped of?

And how do you recognise a situation you should use dynamic memory allocation?

1
  • Note DMA == direct memory access, not dynamic memory allocation Commented Mar 29, 2009 at 15:35

3 Answers 3

7

Another issue for dynamic memory is lifetime. Dynamic memory (new, malloc, etc ...) lives on the heap. It will stay alive until it is explicitly deleted by a piece of code through the appropriate memory function. This is very useful for long lived objects.

Non dynamic memory, or the stack, has a very definite lifetime. The memory allocated on the stack will only be around while that method is executing. Once the method is finished the memory will be automatically reclaimed.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, i think i get it. Every object that should 'survive' the method, should be dynamic allocated?
0

It's very common to not know how many items you have to deal with - they might come from a file or whatever. To store items which come from outside your program you need dynamic sized arrays.

PS: Be sure to use STL classes like std::vector, not "arrays".

Comments

0

You need dynamic allocation when you don't know how many objects you'll need to allocate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.