Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > when to use dynamic memory allocation?

Reply
Thread Tools

when to use dynamic memory allocation?

 
 
xian_hong2046@hotmail.com
Guest
Posts: n/a
 
      04-08-2006
Hello,

I think dynamic memory allocation is supposed to be used when one
doesn't know in advance how much memory to allocate until run time. An
example from Thinking in C++ is to dynamically create an array (using
"new") since one doesn't know it size when writing the program.
However, it looks to me that the size information must come from
somewhere at run time, and this information can be passed to array
creation function as a function's formal argument. Therefore, the
array can still be created using a "static" method. Is this right?

I'd really appreciate it if someone could advise me when to use dynamic
memory allocation.

Many thanks!
xian

 
Reply With Quote
 
 
 
 
Phlip
Guest
Posts: n/a
 
      04-08-2006
xian_hong2046 wrote:

> I think dynamic memory allocation is supposed to be used when one
> doesn't know in advance how much memory to allocate until run time.


Use it if you don't know if you will need an object or not, and if the
object's lifespan must last longer than the function that creates it.

Otherwise, put the object on the stack. It also dynamically allocates, but
synchronized with method calls so you don't need to explicitely delete
things.

> An
> example from Thinking in C++ is to dynamically create an array (using
> "new") since one doesn't know it size when writing the program.


That is a "Thinking in C" topic, because functions like malloc() are the
only way to create a variable-size array in C.

Read /Accelerated C++/, and use std::vector<> to create an array of variable
size. No 'new' or 'delete'. The vector hides them, making your job much
easier and your code much safer.

> However, it looks to me that the size information must come from
> somewhere at run time, and this information can be passed to array
> creation function as a function's formal argument. Therefore, the
> array can still be created using a "static" method. Is this right?


No, because both C and C++ use low-level arrays that are as close to the
metal as possible. Look at this function:

void foo()
{
char slug[99];
...
}

The compiler must know, at compile time, how big to make the foo()
function's stack frame. That's so that (on common implementations) the
compiler can generate the simplest and fastest possible opcodes to create
that stack frame, when foo() starts.

That's why C++ should not permit this:

void foo(int amount)
{
char slug[amount];
....
}

'amount' is not a "hard constant", or "compile time constant". The compiler
cannot guess how big foo's stack frame will be, so it refuses to generate
slower opcodes that calculate this size.

The C languages often make the programmer work a little harder so the
compiler and its output code can work easier and faster.

> I'd really appreciate it if someone could advise me when to use dynamic
> memory allocation.


This is uncompiled code that might contain syntax errors, but it will get
you started:

typedef std::auto_ptr<SimCity> SimCityPointer;

SimCityPointer cityFactory(string type)
{
if ("skyscrapers" == type)
return SimCityPointer(new SkyScraperCity);

if ("ecotopic" == type)
return SimCityPointer(new EcotopicCity);

if ("shanty" == type)
return SimCityPointer(new ShantyCity);

return SimCityPointer(new NullCity);
}

All the *City classes inherit SimCity.

If the user provides a string for what city they want, we create one and
return it.

The calling functions don't care what kind of city it is, hence they can't
create it themselves. If they could, they might put it on the stack, and not
use 'new'.

Because this function decouples the city creation system from the other
functions, it must safely call 'new', and then ensure that functions who use
the city will indeed call 'delete' on it when they are finished with it.

When you call 'new', you should immediately provide a 'delete'. Don't put
that off or try to remember, later after you write many more client
functions, to write a 'delete'. I provided for a delete by putting the
pointer inside the template std::auto_ptr<>.

Discard any C++ tutorial that doesn't discuss smart pointers!

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


 
Reply With Quote
 
 
 
 
xian_hong2046@hotmail.com
Guest
Posts: n/a
 
      04-08-2006
Hi Phlip,

Many thanks for your detailed explanation, that really helped!

xian

 
Reply With Quote
 
Daniel T.
Guest
Posts: n/a
 
      04-08-2006
In article <(E-Mail Removed) .com>,
"(E-Mail Removed)" <(E-Mail Removed)> wrote:

> Hello,
>
> I think dynamic memory allocation is supposed to be used when one
> doesn't know in advance how much memory to allocate until run time. An
> example from Thinking in C++ is to dynamically create an array (using
> "new") since one doesn't know it size when writing the program.


Those kinds of issues are addressed in the standard library. If you
don't know how many objects you need until runtime, use a container.

> I'd really appreciate it if someone could advise me when to use dynamic
> memory allocation.


You should use dynamic memory allocation directly when you don't know
the *type* of the object you are creating until runtime.


--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
 
Reply With Quote
 
Daniel T.
Guest
Posts: n/a
 
      04-09-2006
In article <mzHZf.9128$%(E-Mail Removed)> ,
"Phlip" <(E-Mail Removed)> wrote:

> xian_hong2046 wrote:
>
> > I think dynamic memory allocation is supposed to be used when one
> > doesn't know in advance how much memory to allocate until run time.

>
> Use it if you don't know if you will need an object or not, and if the
> object's lifespan must last longer than the function that creates it.


I think that the above isn't general enough. For example, a constructor
can create an object, and the destructor destroy it, without it being
newed or deleted.

I was think of some rule like "if the scopes don't match" but you can
always create a scope that matches the objects lifetime so that doesn't
work either...

> > I'd really appreciate it if someone could advise me when to use dynamic
> > memory allocation.

>
> This is uncompiled code that might contain syntax errors, but it will get
> you started:
>
> typedef std::auto_ptr<SimCity> SimCityPointer;
>
> SimCityPointer cityFactory(string type)
> {
> if ("skyscrapers" == type)
> return SimCityPointer(new SkyScraperCity);
>
> if ("ecotopic" == type)
> return SimCityPointer(new EcotopicCity);
>
> if ("shanty" == type)
> return SimCityPointer(new ShantyCity);
>
> return SimCityPointer(new NullCity);
> }
>
> All the *City classes inherit SimCity.
>
> If the user provides a string for what city they want, we create one and
> return it.
>
> The calling functions don't care what kind of city it is, hence they can't
> create it themselves. If they could, they might put it on the stack, and not
> use 'new'.
>
> Because this function decouples the city creation system from the other
> functions, it must safely call 'new', and then ensure that functions who use
> the city will indeed call 'delete' on it when they are finished with it.


The above is a good explanation but it doesn't match the general rule
given, your using 'new' because you don't know what type of city you
will need until runtime, not because it outlives the function.


--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
 
Reply With Quote
 
Phlip
Guest
Posts: n/a
 
      04-09-2006
Daniel T. wrote:

>> Use it if you don't know if you will need an object or not, and if the
>> object's lifespan must last longer than the function that creates it.

>
> I think that the above isn't general enough. For example, a constructor
> can create an object, and the destructor destroy it, without it being
> newed or deleted.
>
> I was think of some rule like "if the scopes don't match" but you can
> always create a scope that matches the objects lifetime so that doesn't
> work either...


The goal here is to find just the right verbiage that leads no newbie
astray, but doesn't depend on the advanced terms like "scope" or "RAII" or
"deterministic destruction".

So, "don't call 'new' until you exhaust the simpler alternatives", and
"vector is simpler than new[] for arrays".

> The above is a good explanation but it doesn't match the general rule
> given, your using 'new' because you don't know what type of city you
> will need until runtime, not because it outlives the function.


Right. I'm so advanced that I can't think of the simplest possible scenario
that demands 'new'.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


 
Reply With Quote
 
Daniel T.
Guest
Posts: n/a
 
      04-09-2006
In article <4sZZf.23724$(E-Mail Removed)> ,
"Phlip" <(E-Mail Removed)> wrote:

> Daniel T. wrote:
>
> > The above is a good explanation but it doesn't match the general rule
> > given, your using 'new' because you don't know what type of city you
> > will need until runtime, not because it outlives the function.

>
> Right. I'm so advanced that I can't think of the simplest possible scenario
> that demands 'new'.


I disagree, you aren't that advanced. That *is* the simplest
possible scenario that demands 'new'. The only time that 'new' is
demanded is when you don't know what sub-type to make until runtime.


--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
 
Reply With Quote
 
xian_hong2046@hotmail.com
Guest
Posts: n/a
 
      04-09-2006
Hi Daniel and Phlip,

Thanks to both of you for the discussions, I find them very useful
indeed.

May I please ask you another two questions, which may be quite trivial
to you?

I had a simple file like:

#include <iostream>
using namespace std;

int i;

i = 10;
int main(){
cout << i << endl;
}

But it couldn't compile. However, if I combined the declarations and
definitions of "i" into one:

int i = 10

then it all worked out. It also worked if I moved "i=10" into the body
of "main". What's the problem?

Another question concerns the use of "extern". It should be used when
one declares a function or variable that has been defined in another
file or will be defined later in this file. If the variable/function
is declared in a .h file (but no definitions are provided in the .h
file), then after I include the header file, do I still need to use
"extern" before I use that function/variable? From my experiments, it
looks like I don't have to. But according to the purpose of "extern",
it seems that I should use "extern".

Many thanks,
xian

 
Reply With Quote
 
Phlip
Guest
Posts: n/a
 
      04-09-2006
Daniel T. wrote:

> The only time that 'new' is
> demanded is when you don't know what sub-type to make until runtime.


A. What example would you give an absolute new newbie?

B. I'm certain I have used new for simpler situations. I'm aware
some of them could have been NullObjects, or the equivalent.
Are you convinced that's the _only_ time new is demanded??

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
 
Reply With Quote
 
Phlip
Guest
Posts: n/a
 
      04-09-2006
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:

> int i;
>
> i = 10;
> int main(){
> cout << i << endl;
> }


Only declarations, definitions, and initializations may appear outside of
functions or constructors. (And namespaces, typedefs, preprocessor
statements, and other bric-a-brac that some language lawyer wannabe is sure
to jump all over me about.)

This is permitted outside of functions:

> int i = 10


i = 10; is not because it's not part of the action of defining x.
Initialization is.

> Another question concerns the use of "extern". It should be used when
> one declares a function or variable that has been defined in another
> file or will be defined later in this file. If the variable/function
> is declared in a .h file (but no definitions are provided in the .h
> file), then after I include the header file, do I still need to use
> "extern" before I use that function/variable? From my experiments, it
> looks like I don't have to. But according to the purpose of "extern",
> it seems that I should use "extern".


It's optional on function declarations and not

The deal here is a "translation unit" that's usually one .cpp file that
creates one .o or .obj file. After you put all the .h files together
into .cpp file, the result is a "translation unit" that then gets compiled
into opcodes.

For a given global int Foo, all translation units that need the Foo should
see an 'extern int Foo;'. But only one translation unit needs 'int Foo =
42;'. That's so the opcodes that create the Foo itself will only compile in
one spot, and only go into one .o or .obj file.

Now don't use extern, and learn not to make global variables. Make global
functions instead, so the code stays more flexible.

>
> Many thanks,
> xian


--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
String’s static memory vs dynamic memory? Nephi Immortal C++ 1 01-04-2013 07:47 AM
static memory allocation versus dynamic memory allocation Ken C Programming 24 11-30-2006 12:37 AM
Dynamic memory allocation and memory leak... s.subbarayan C Programming 10 03-22-2005 02:48 PM
Storage devices which can use Memory Stick Pro memory cards arouth@radiology.umsmed.edu Digital Photography 1 01-17-2005 11:14 AM
Differences between Sony Memory Stick & memory Stick Pro vs Memory Stick Duo? zxcvar Digital Photography 3 11-28-2004 10:48 PM



Advertisments