Stack and Heap

S

sarathy

Hi all,
I need a few clarifications regarding memory allocaion in C++.
I apologize for the lengthy explanation.

1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

2. In C++, functions and its local variables go in stack.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

2.1 Do they go in heap or in stack?
2.1.1 If they go in heap, then how will the local stack variable gain
access to an object in heap. Does the compiler maintain any object
reference internally? ( I have read about memory allocation in Java,
where in object references are being stored in the variable rather than
the object itself. Hence it is completely OK, since the local reference
in method can refer to an object in heap, since they have the reference
available with them.)

2.1.2 If they go in stack, then can objects reside in Stack?

3. Will 2 have the same effect on the following 2 cases.

Object a;
Object b = new Object();

i.e Is the memory allocation for both Object a and b same. I
understand that the memory created by "new" should be explicitly
destroyed using "delete". [Let us assume that i am not overloading new
and delete]. But other than that, is there any difference between
memory allocation for object a and b. If no, then how will the rules in
2 affect them.

4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

Thanks and regards,
Sarathy
 
T

Tommo

1. Not true. Objects created with new are created on the heap, all
other are on the stack. You may want some objects to live in ( passed
your immediate scope usage ) and so you would use new

Object a; - on stack
Object* b = new Object; - on heap

2. All variables unless created with new go on the stack

generally if you create an object as follows

Object* b = new Object.

The pointer b lives on the stack but the object itself lives on in the
heap. The reason you need to make sure you delete Objects is if you
code goes out of scope ( out of nearest set of braces {} ) then the
pointer b will no longer exist and you will be left with an object on
the heap that has no references to it i.e memory leak

note the new operator return you a pointer to an object so you can't
do:

Object b = new Object; you must use

Object* b = new Object.

Also note that if you create an object using the default constructor
you may create an object using

Object* b = new Object;
or
Object* b = new Object().

Hope this helps
 
H

Heinz Ozwirk

sarathy said:
Hi all,
I need a few clarifications regarding memory allocaion in C++.
I apologize for the lengthy explanation.

First of all, C++ does not know of a stack or heap, except for some data
types like std::stack.

Basically C++ defines three ways to allocate memory for variables:

Static allocation is used for global and static variables.
Automatic allocation is used for local variables inside functions.
The free store is used for variables allocated with new, malloc and similiar
functions.

As it happens, a stack is often used to implement automatic allocation and
some people call the memory available to new a heap, but the standard does
not require to use a stack for automatic allocation.
1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

In C++ objects are allocated as the programmer wants them to be allocated.
If he defines an object as a global variable, the object is allocated with
all other global variables; if the object is defined as a local variable,
the objects is allocated like any other local variable; and if the object is
allocated using new, the object is allocated in the memory provided by the
new operator.
2. In C++, functions and its local variables go in stack.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

The stack, if there really is one, is commonly used for local variables,
function parameters, return addresses and other data needed to keep the
program running, but never for functions. Functions may use the stack (or
whatever local variables are allocated in), but they are never part of that
memory. A function itself is code, and usually code and data are kept apart,
at least conceptually.

Where in memory a variable's data will be stored depends on how the variable
has been defined, but not on the type of the variable. A local variable is
always allocated "on the stack", regardless of its type. int's and whatever
user defined type you are using are treated in exacly the same way.

Unlike other languages, C++ does not distinguish between value types and
reference types, and it does not distinguish between primitive types and
objects. Anything, that can be assigned to some variable, is an object.
2.1 Do they go in heap or in stack?
Yes.

2.1.1 If they go in heap, then how will the local stack variable gain
access to an object in heap. Does the compiler maintain any object
reference internally? ( I have read about memory allocation in Java,
where in object references are being stored in the variable rather than
the object itself. Hence it is completely OK, since the local reference
in method can refer to an object in heap, since they have the reference
available with them.)

A variable is a pair, the name of the object and the object itself. It is up
to the compiler (or its implementor) how the compiler assiciates the name of
the object with the object itself.
2.1.2 If they go in stack, then can objects reside in Stack?
Yes.

3. Will 2 have the same effect on the following 2 cases.

Object a;
Object b = new Object();

That is Java or C#, but not valid C++. new returns a pointer, and pointers
can only be stored in variables of pointer type.

If you want a local object that is destroyed when its name becomes
invisible, use

Object a,

When you want an object that stays alive even if execution leaves the scope
of its allocation, use

Object* b = new Object;
i.e Is the memory allocation for both Object a and b same. I
understand that the memory created by "new" should be explicitly
destroyed using "delete". [Let us assume that i am not overloading new
and delete]. But other than that, is there any difference between
memory allocation for object a and b. If no, then how will the rules in
2 affect them.

4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

There is no big difference between "heap" and "free store". Better think of
the as two differnt names for the same thing.

One last advice. When writing C++ code, try to forget everything you know
about Java, especially about its object management. It's complety different
from what you are doing in C++.

HTH
Heinz
 
J

Jerry Coffin

[ ... ]
1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

The usual terminology in C++ is that objects are allocated from the free
store. The "heap" is normally reserved for referring to memory managed
with malloc/calloc/realloc/free. The code that controls each of these
normally uses some sort of data structure to manage the memory, but the
exact structure they use is unspecified by the standard -- but I don't
recall ever having seen or heard of one that used a heap data structure.
2. In C++, functions and its local variables go in stack.

No -- the memory for a function itself is normally statically allocated.
i.e. the function is simply loaded somewhere in memory, and that's the
end of that. Other than the fact that you can take the address of a
function and assign it to a pointer to a function, C++ doesn't have much
to say about the memory used for functions themselves.

Local variables are allocated/freed in a stack-like (LIFO) manner, so
it's common to refer to that memory as the stack, but C++ doesn't have
any real requirements beyond how it acts in general (i.e. it's available
as soon as code in the function starts to execute, and it's no longer
avaiable after the function returns.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

What about them?
2.1 Do they go in heap or in stack?

If you declare them as automatic variables, they go on the stack (i.e.
they are managed automatically). If you declare them as global objects,
then they'll be statically allocated (as a rule).

[ ... ]
2.1.2 If they go in stack, then can objects reside in Stack?

Officially, as noted above, there is no stack. Unofficially, yes,
objects can and often will reside on the stack.
3. Will 2 have the same effect on the following 2 cases.

Object a;

The effect of this depends on its location. If it's inside of a
function, a will be an auto object, which means it'll live on the stack
(to the extent that there is one).
Object b = new Object();

The effect of this is simpler: it won't compile. new returns a pointer
to an object, so if you're going to use new, the thing you assign its
result to needs to be a pointer (unless you use a type-cast to coerce it
to some other type...)

Object *b = new Object;

would compile. This creates a pointer variable named b in automatic
storage (i.e. on the stack). That variable is initialized with the
address of an Object created on the free store.

Note: such code is unusual in well-written C++. It's usually the result
of a Java or Smalltalk programmer trying to write C++, not anything that
there was a good reason to do in C++.
i.e Is the memory allocation for both Object a and b same.

Yes and no. a is an Object with automatic storage. b is a pointer with
automatic storage, but the Object it's pointing at has dynamic storage.
So a and b themselves are allocated simlilarly, but a is an Object where
b is a pointer, and the Object b is pointing at is allocated entirely
differently from the object a.

[ ... ]
4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

The heap is managed by malloc/calloc/realloc/free. The free store is
managed with new and delete. There are two "big deal"s: first, don't try
to mix the two (e.g. don't delete something that was malloc'd or free
something that was new'ed). Second, what you allocate with malloc is raw
memory, NOT an object. You can use it for POD classes (i.e. a type that
would be recognized by a C compiler), but not for any fancier class
types, such as anything with a constructor or any virtual functions.*

Most C++ code that's really written as C++ code (rather than C that's
compatible with a C++ compiler) never has any reason to use the heap at
all. Use of the free store is usually wrapped up in a class that's
dedicated primarily to managing that piece of storage (e.g the standard
library's collection classes).

1. For any pedants looking on: yes, I know you can allocate memory and
then use placement new to create an object in that memory on the heap --
but under the circumstances this is probably better ignored.
 
S

sarathy

1.
There is no big difference between "heap" and "free store". Better think of
the as two differnt names for the same thing.

Free Store The free store is one of the two dynamic memory
areas, allocated/freed by new/delete.

Heap The heap is the other dynamic memory area,
allocated/freed by malloc/free and their
variants.

I realize that there are 2 memory regions for dynamic memory allocation
[ heap and free store ]. Is there any real significance in the concept
of free store in C++ inspite of heap's presence. Because i remember
heaps being used in C too. So why free store ?

2.
In C++ objects are allocated as the programmer wants them to be allocated.
If he defines an object as a global variable, the object is allocated with
all other global variables; if the object is defined as a local variable,
the objects is allocated like any other local variable; and if the object is
allocated using new, the object is allocated in the memory provided by the
new operator.


Consider the following piece of code.

class Person
{
private:
int age;

public:
Person() { age=0; }
Person(int a) { age=a; }
int getAge() { return age; }
void setAge(int a) { age=a; }
};

int main()
{
Person *p1 = new Person;
Person p2;
}

I have absolutely no problem with p1, as i have explicitly mentioned to
allocate memory using new, which implies that FREE STORE memory will be
used [ or if the compiler has used malloc, free internally, then HEAP
will be used ]

According to our discussion, p2 is an object which will be allocated
in STACK. I beleive that memory can be allocated to objects either only
by

1. new/delete
2. malloc/free variants.

If even the compiler uses any 1 of them internally, then the objects
will go to free store or heap. If that is the case, how is it validated
that p2 is allocated in stack.

[ OR ]

Is there any other mechanism which is used to allocate memory to
objects? [ Like the one which allocates p2 to stack]. If yes can i use
it to explicitly allocate an object in stack, rather than going for
Free store or Heap.

Thanks and Regards,
Sarathy
 
I

Ian Collins

sarathy wrote:

Please don't snip attributions, it's considered rude on Usenet
1.



Free Store The free store is one of the two dynamic memory
areas, allocated/freed by new/delete.

Heap The heap is the other dynamic memory area,
allocated/freed by malloc/free and their
variants.
No, wrong. Read what Heinz posted again, the terms are synonymous.
I realize that there are 2 memory regions for dynamic memory allocation
[ heap and free store ]. Is there any real significance in the concept
of free store in C++ inspite of heap's presence. Because i remember
heaps being used in C too. So why free store ?
Same misunderstanding. In practical implementations, there isn't a
difference between C and C++ memory models.
Consider the following piece of code.
int main()
{
Person *p1 = new Person;
Person p2;
}

I have absolutely no problem with p1, as i have explicitly mentioned to
allocate memory using new, which implies that FREE STORE memory will be
used [ or if the compiler has used malloc, free internally, then HEAP
will be used ]
Same misunderstanding.
According to our discussion, p2 is an object which will be allocated
in STACK. I beleive that memory can be allocated to objects either only
by

1. new/delete
2. malloc/free variants.
No. new/delete and malloc/free both use free store. p2 is automatic
object, which will be on the stack if the implementation uses one.
Is there any other mechanism which is used to allocate memory to
objects? [ Like the one which allocates p2 to stack].

Not as part of standard C++.
 
T

toton

Jerry said:
[ ... ]
1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

The usual terminology in C++ is that objects are allocated from the free
store. The "heap" is normally reserved for referring to memory managed
with malloc/calloc/realloc/free. The code that controls each of these
normally uses some sort of data structure to manage the memory, but the
exact structure they use is unspecified by the standard -- but I don't
recall ever having seen or heard of one that used a heap data structure.
2. In C++, functions and its local variables go in stack.

No -- the memory for a function itself is normally statically allocated.
i.e. the function is simply loaded somewhere in memory, and that's the
end of that. Other than the fact that you can take the address of a
function and assign it to a pointer to a function, C++ doesn't have much
to say about the memory used for functions themselves.

Local variables are allocated/freed in a stack-like (LIFO) manner, so
it's common to refer to that memory as the stack, but C++ doesn't have
any real requirements beyond how it acts in general (i.e. it's available
as soon as code in the function starts to execute, and it's no longer
avaiable after the function returns.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

What about them?
2.1 Do they go in heap or in stack?

If you declare them as automatic variables, they go on the stack (i.e.
they are managed automatically). If you declare them as global objects,
then they'll be statically allocated (as a rule).

[ ... ]
2.1.2 If they go in stack, then can objects reside in Stack?

Officially, as noted above, there is no stack. Unofficially, yes,
objects can and often will reside on the stack.
3. Will 2 have the same effect on the following 2 cases.

Object a;

The effect of this depends on its location. If it's inside of a
function, a will be an auto object, which means it'll live on the stack
(to the extent that there is one).
Object b = new Object();

The effect of this is simpler: it won't compile. new returns a pointer
to an object, so if you're going to use new, the thing you assign its
result to needs to be a pointer (unless you use a type-cast to coerce it
to some other type...)

Object *b = new Object;

would compile. This creates a pointer variable named b in automatic
storage (i.e. on the stack). That variable is initialized with the
address of an Object created on the free store.

Note: such code is unusual in well-written C++. It's usually the result
of a Java or Smalltalk programmer trying to write C++, not anything that
there was a good reason to do in C++.
i.e Is the memory allocation for both Object a and b same.

Yes and no. a is an Object with automatic storage. b is a pointer with
automatic storage, but the Object it's pointing at has dynamic storage.
So a and b themselves are allocated simlilarly, but a is an Object where
b is a pointer, and the Object b is pointing at is allocated entirely
differently from the object a.

[ ... ]
4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

The heap is managed by malloc/calloc/realloc/free. The free store is
managed with new and delete. There are two "big deal"s: first, don't try
to mix the two (e.g. don't delete something that was malloc'd or free
something that was new'ed). Second, what you allocate with malloc is raw
memory, NOT an object. You can use it for POD classes (i.e. a type that
would be recognized by a C compiler), but not for any fancier class
types, such as anything with a constructor or any virtual functions.*

Most C++ code that's really written as C++ code (rather than C that's
compatible with a C++ compiler) never has any reason to use the heap at
all. Use of the free store is usually wrapped up in a class that's
dedicated primarily to managing that piece of storage (e.g the standard
library's collection classes).
I object this point. C++ (or C or any language) has give dynamic memory
allocation, and there is reason for this. It is very much needed for
nearly every program, which needs tochange their behavior ar runtime.
Don't stl containers, strings etc use dynamic memory allocation?
How will u do, if u want to add a object or its children to a container
class, whitout storing the pointer in the container?
In a GUI container, if u want to add another button when user do
something, or flus certain message, how will u do it without dynamic
memory allocation? I dont expect u to allocate for all such objects at
prior.
C++ is a OO language, and its main strength (like any other OOL) is
the virtual function. (that is the first + ) . The thing is not
possible without a new and delete (in turn dynamic allocation, may be
using auto_ptr or whatever) .
The main point in a OOL is getting an interface (a class with pure
virtual functions) and implement it. The client will get a
implementation for the known interface and call the dynamically binded
implementations on it.

I don't thing it is possible to survive without dynamic allocation, if
u r doing a commercial grade project.
maybe C++'s biggest flaw is to return a pointer with dynamic creation
rather than a reference (another I thing interface keyword).
1. For any pedants looking on: yes, I know you can allocate memory and
then use placement new to create an object in that memory on the heap --
but under the circumstances this is probably better ignored.
Most of the time not needed, but need to know surely, one can have
beautiful programming with placement new (not hacked, a true program) .
 
I

Ian Collins

toton said:
Jerry Coffin wrote:

I object this point. C++ (or C or any language) has give dynamic memory
allocation, and there is reason for this. It is very much needed for
nearly every program, which needs tochange their behavior ar runtime.
Don't stl containers, strings etc use dynamic memory allocation?
How will u do, if u want to add a object or its children to a container
class, whitout storing the pointer in the container?

Please don't use abbreviations like 'u', they make you post hard to read.

None of the C++, with the exception of containers, I have over the past
couple of years uses new or delete. Sure dynamic allocation is used
throughout, but it is always wrapped up in a container or smart pointer
type object rather than in the raw. I think that was Jerry's point.
I don't thing it is possible to survive without dynamic allocation, if
u r doing a commercial grade project.

No one is disputing that.
maybe C++'s biggest flaw is to return a pointer with dynamic creation
rather than a reference (another I thing interface keyword).
That's why I prefer to wrap dynamic objects.
 
T

toton

Ian said:
Please don't use abbreviations like 'u', they make you post hard to read.

None of the C++, with the exception of containers, I have over the past
couple of years uses new or delete. Sure dynamic allocation is used
throughout, but it is always wrapped up in a container or smart pointer
type object rather than in the raw. I think that was Jerry's point.


No one is disputing that.
The point was made, heap (free store) is not needed except C++ std
collections. There are a lot more than the std library. They all need
free store. Even users of those library needs free store.
That's why I prefer to wrap dynamic objects.
VCF is the most modern Framework which heavily uses c++ std. Qt is
slightly older. Apache has a number of C++ based projects. One can
count on new in the source codes . delete is less, as most wise people
use auto_ptr or some of the boost pointers, or reference counting.

I see a problem with delete. But what is the problem with new? If one
needs dynamic memory , he needs new.
How will I add a Button in a Window when user clicks something?
either by Button* pButton = new ImageButton("OK");
this->add(pButton,AlignTop) ; (I may not use auto_ptr like
auto_ptr<Button> pButton(new Button("OK")); here, as it will be most
probably be already reference counted, or container like Window will
take the responsibility of deleting it when added to it, I dont have to
worry to delete pButton ) or
or Button* pButton = Button::createImageButton("OK"); ,i.e using named
constructor.
 
I

Ian Collins

toton said:
The point was made, heap (free store) is not needed except C++ std
collections. There are a lot more than the std library. They all need
free store. Even users of those library needs free store.
I read the comment as not used directly, but still used indirectly.
Which is true. One doesn't use new to create an object, rather one uses
some factory method to obtain a smart pointer object that wraps the object.

The XML DOM code I use for web page generation used dynamic objects
under the hood, but all my page generation uses statements like

Element p = document.createElement("p");

Element is a smart pointer type, document.createElement() is a factory
method.
I see a problem with delete. But what is the problem with new? If one
needs dynamic memory , he needs new.
How will I add a Button in a Window when user clicks something?
either by Button* pButton = new ImageButton("OK");

or an interface like my DOM,

Button buttom = window.createImageButton("OK");
this->add(pButton,AlignTop) ; (I may not use auto_ptr like
auto_ptr<Button> pButton(new Button("OK")); here, as it will be most
probably be already reference counted, or container like Window will
take the responsibility of deleting it when added to it, I dont have to
worry to delete pButton ) or
or Button* pButton = Button::createImageButton("OK"); ,i.e using named
constructor.
Yes, that would be the preferred way if you are using raw pointers.
 
T

toton

Ian said:
I read the comment as not used directly, but still used indirectly.
Which is true. One doesn't use new to create an object, rather one uses
some factory method to obtain a smart pointer object that wraps the object.

The XML DOM code I use for web page generation used dynamic objects
under the hood, but all my page generation uses statements like

Element p = document.createElement("p");

Element is a smart pointer type, document.createElement() is a factory
method.
It is possible, as document creates the element. Thus it can add a
reference to itself, and delete the object when it gets deleted.
or an interface like my DOM,

Button buttom = window.createImageButton("OK");
Problem here. This should be client's code, and one defined in API, as
window doesn't know all of the components available, or about any 3rd
party component ( may be something like RoundedButton ?)Thus usual way of writing in most of the cases,
1) Button* btn = new Button("OK"); //potential chance for memory lick,
if one doesn't do a delete or write the next line.
this->add(btn,AlignTop);
2) Button* btn = new Button("OK",this); //safer, no fear for memory
leak. but fear of deleting a pointer when it is owned by container.
like delete btn;
3) ref said:
Yes, that would be the preferred way if you are using raw pointers.
4) if your API don't support 2) or 3) kind of object creation (most of
them don't) , Use a factory for creating controls in the client code. I
usually use UIFactory, which has,
Button& createButton(const string& name, const string& image, Window*
parent){} etc.
where I usually add the two steps of component creation.
Only problem still persists here is, someone gets the reference to the
button inside window, passes it outside and kills the window! better to
pass a reference, which is counted (like smart pointer in your example)

Infact people are creazy! I have seen someone who reuses common Buttons
(like OK Cancel etc) instead of creating them each time the dialog or
window needs it. They creates them first time, cache them, if many
window asks, returns a copy, and reference count them, and clear cache
upon request!
I sometimes don't allocate memory for objects, when time comes, init it
in the pre-created memory pool (placement new) , use it, and destory
(deinitialize) after that. They are very light, as the major part ,
like memory allocation is done in a pool. Many character renderer use
that technique also. Alternative may be a pre-created object pool, and
change the object itself using setters, but looks little ugly.

Ultimately, it boils down to the fact, that everything can't be treated
same way. May be for most of the cases stl, standard smart ptr etc
works, but still some special case always exist which needs to be
treated differently. And there is beauty of C++ lies, one can take
precise control of the system, if one needs to do so.
Simple Java like create & forget approach is not always good (Java has
a sofisticated gc and memory management, which C++ lacks), a little
"personal touch" is sometimes necessary :) .

thanks ...
 
I

Ian Collins

toton said:
It is possible, as document creates the element. Thus it can add a
reference to itself, and delete the object when it gets deleted.
That's one way and a common on one for GUI toolkits. The other is for
Element to be a self contained reference counted object. I find the
latter conceptually better and easier to implement.
Problem here. This should be client's code, and one defined in API, as
window doesn't know all of the components available, or about any 3rd
party component ( may be something like RoundedButton ?)
RoundedButton button = window.createWidget<RoundedButton>("OK");

Thus usual way of writing in most of the cases,
1) Button* btn = new Button("OK"); //potential chance for memory lick,
if one doesn't do a delete or write the next line.
this->add(btn,AlignTop);
2) Button* btn = new Button("OK",this); //safer, no fear for memory
leak. but fear of deleting a pointer when it is owned by container.
like delete btn;


4) if your API don't support 2) or 3) kind of object creation (most of
them don't) , Use a factory for creating controls in the client code. I
usually use UIFactory, which has,
Button& createButton(const string& name, const string& image, Window*
parent){} etc.
where I usually add the two steps of component creation.
Only problem still persists here is, someone gets the reference to the
button inside window, passes it outside and kills the window! better to
pass a reference, which is counted (like smart pointer in your example)
That's the problem I set out to resolve when I took the "everything is a
self-contained object" approach.

One interesting side effect is that the C++ code is also valid Java,
JavaScript and (with the addition of a couple of '$'s) PHP. Which makes
coded generation a snip.
Infact people are creazy! I have seen someone who reuses common Buttons
(like OK Cancel etc) instead of creating them each time the dialog or
window needs it. They creates them first time, cache them, if many
window asks, returns a copy, and reference count them, and clear cache
upon request!

If Buttons are self-contained, the object management problems go away.
I sometimes don't allocate memory for objects, when time comes, init it
in the pre-created memory pool (placement new) , use it, and destory
(deinitialize) after that. They are very light, as the major part ,
like memory allocation is done in a pool. Many character renderer use
that technique also. Alternative may be a pre-created object pool, and
change the object itself using setters, but looks little ugly.
A valid technique, provided you don't expose the working to the user!
Ultimately, it boils down to the fact, that everything can't be treated
same way. May be for most of the cases stl, standard smart ptr etc
works, but still some special case always exist which needs to be
treated differently. And there is beauty of C++ lies, one can take
precise control of the system, if one needs to do so.

A big +1 to that.
Simple Java like create & forget approach is not always good (Java has
a sofisticated gc and memory management, which C++ lacks), a little
"personal touch" is sometimes necessary :) .
Indeed, but don't forget we can do it better with RAII.
 
J

Jerry Coffin

[ ... ]
I object this point. C++ (or C or any language) has give dynamic memory
allocation, and there is reason for this. It is very much needed for
nearly every program, which needs tochange their behavior ar runtime.
Don't stl containers, strings etc use dynamic memory allocation?
How will u do, if u want to add a object or its children to a container
class, whitout storing the pointer in the container?

"e.g." means "for example". Using the standard library containers as an
example doesn't mean they have exclusive rights to using dynamic
allocation -- only that they (at least for the most part) do a pretty
decent job. In particular, the containers themselves mostly stick to a
single job of managing a single, fairly specific data structure apiece.
They don't, for one example, attempt to implement all (or even most) of
the algorithms that could reasonably be carried out on that data
structure -- they only implement things that require/use special
internal knowledge.

[ ... ]
C++ is a OO language, and its main strength (like any other OOL) is
the virtual function. (that is the first + ) . The thing is not
possible without a new and delete (in turn dynamic allocation, may be
using auto_ptr or whatever) .

Actually, it's entirely possible to use virtual functions without
dynamic allocation, but it's more or less beside the point -- I didn't
say there was anything wrong with using dynamic allocation in the first
place.
Most of the time not needed, but need to know surely, one can have
beautiful programming with placement new (not hacked, a true program) .

Yes, at some point it's a good thing to know eventually -- but for
somebody who's just trying to sort out the basics it's pointless.
 
T

Thomas Matthews

sarathy said:
Hi all,
I need a few clarifications regarding memory allocaion in C++.
I apologize for the lengthy explanation.

1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

2. In C++, functions and its local variables go in stack.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

2.1 Do they go in heap or in stack?
2.1.1 If they go in heap, then how will the local stack variable gain
access to an object in heap. Does the compiler maintain any object
reference internally? ( I have read about memory allocation in Java,
where in object references are being stored in the variable rather than
the object itself. Hence it is completely OK, since the local reference
in method can refer to an object in heap, since they have the reference
available with them.)

2.1.2 If they go in stack, then can objects reside in Stack?

3. Will 2 have the same effect on the following 2 cases.

Object a;
Object b = new Object();

i.e Is the memory allocation for both Object a and b same. I
understand that the memory created by "new" should be explicitly
destroyed using "delete". [Let us assume that i am not overloading new
and delete]. But other than that, is there any difference between
memory allocation for object a and b. If no, then how will the rules in
2 affect them.

4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

Thanks and regards,
Sarathy
Tommo said:
> 1. Not true. Objects created with new are created on the heap, all
> other are on the stack. You may want some objects to live in ( passed
> your immediate scope usage ) and so you would use new
>
> Object a; - on stack

Not true. Depends on where it is declared and the compiler /
implementation.
A variable defined outside of a function is an automatic variable.
Many implementations place these global variables (including variables
declared as static inside blocks} into an area of memory that is
neither heap nor stack. It is a fixed area of memory.

> Object* b = new Object; - on heap
>
> 2. All variables unless created with new go on the stack
>
> generally if you create an object as follows
>
> Object* b = new Object.
>
> The pointer b lives on the stack but the object itself lives on in the
> heap. The reason you need to make sure you delete Objects is if you
> code goes out of scope ( out of nearest set of braces {} ) then the
> pointer b will no longer exist and you will be left with an object on
> the heap that has no references to it i.e memory leak

Again, depends on where and how the pointer is declared. See above.
>
> note the new operator return you a pointer to an object so you can't
> do:
>
> Object b = new Object; you must use
>
> Object* b = new Object.
>
> Also note that if you create an object using the default constructor
> you may create an object using
>
> Object* b = new Object;
> or
> Object* b = new Object().
>
> Hope this helps

Please read and study about automatic variables, global scope and
local scope.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
 
T

toton

Thomas said:
sarathy said:
Hi all,
I need a few clarifications regarding memory allocaion in C++.
I apologize for the lengthy explanation.

1. In C++, Objects are allocated in heap.
What does heap refer to? Is it an area in RAM/Memory or does it refer
to a data structure being used for storing objects.

2. In C++, functions and its local variables go in stack.
If local variables that are primitives go in stack, it is OK. But what
about local variables that are objects.

2.1 Do they go in heap or in stack?
2.1.1 If they go in heap, then how will the local stack variable gain
access to an object in heap. Does the compiler maintain any object
reference internally? ( I have read about memory allocation in Java,
where in object references are being stored in the variable rather than
the object itself. Hence it is completely OK, since the local reference
in method can refer to an object in heap, since they have the reference
available with them.)

2.1.2 If they go in stack, then can objects reside in Stack?

3. Will 2 have the same effect on the following 2 cases.

Object a;
Object b = new Object();

i.e Is the memory allocation for both Object a and b same. I
understand that the memory created by "new" should be explicitly
destroyed using "delete". [Let us assume that i am not overloading new
and delete]. But other than that, is there any difference between
memory allocation for object a and b. If no, then how will the rules in
2 affect them.

4. I've read that C++ maintains, 2 memory locations to store objects
namely "heap" and "free store". Is there any big deal in it?

Thanks and regards,
Sarathy
Tommo said:
1. Not true. Objects created with new are created on the heap, all
other are on the stack. You may want some objects to live in ( passed
your immediate scope usage ) and so you would use new

Object a; - on stack

Not true. Depends on where it is declared and the compiler /
implementation.
A variable defined outside of a function is an automatic variable.
Many implementations place these global variables (including variables
declared as static inside blocks} into an area of memory that is
neither heap nor stack. It is a fixed area of memory.

Depends what heap and stack means.
A static allocation becomes inaccessable when the object goes out of
scope ( a behavior similar to stack), while a dynamic allocation do
not. (dynamic allocation becomes inaccessable when one looses the
pointer ! or deletes it).
dynamic allocation marks a memory as free, when object gets deleted.
static allocation sets the pointer to the location (most of time) to
proper stack frame location.
Both can be made inexpensive. but for allocating memory on stack need
not to search the memory availability, as it knows it is available
where the frame ptr is just resides, which is needed for heap
allocation. Again they can be interchanged easily, when one knows the
class is not getting extended virtually.
Thus it is wrong to say, dynamic allocation is costly kind of statement
(but most C++ implementation, they are little costly than static). It
is better to say, allocating in heap is little costlier than allocating
in stack frame. also most of the microprocessor supports stack frame
directly. There can be many kind of other memory allocation done (one
is free to think static storage/buffer , queue, and all other kind of
data structure.), but they do not affect the fact that static
allocation is inaccessible if it goes out of scope (the object still
may very much exist in the memory, but assured that it is marked as
free), while dynamic allocation is not.
So,
1) Object* o = new Object(); is dynamic (may be stack heap or whatever
it is, but mostly heap)
and
2) Object o = Object(); is static (may be stack, heap or any other
structure, but mostly stack frame).
One more point, there is no reason to think 1) is costiler than 2),
there is no such rule. but in most of the implementation is like so.
( I know Java dynamic memory allocation has object inlining, based on
final , GCC also has it, making dynamic allocation sometimes even
faster than static!)
Lastly, heap based allocation is extremely flexible, when classes
change dynamically, or multi processing environment, distributed
computing etc, or even when object allocates large resource. Also it is
not that in heap allocation, memory is distributed all over, most
implementation just translate the TLB rather than data, and so a
distributed memory looks continuous for the processor.
 
T

toton

Ian said:
That's one way and a common on one for GUI toolkits. The other is for
Element to be a self contained reference counted object. I find the
latter conceptually better and easier to implement.

RoundedButton button = window.createWidget<RoundedButton>("OK");

Should do the trick, I have a similar templated createElement<>() method
in my DOM Document class.
May be! One can do it happily in his Linux box. I am not as lucky as
you :(
I mostly program for embedded devices. And standard is not supported by
most of the compilers. There the practical thumb rule is, use template
as less as you can, though it may look a bad idea! One can't entirely
blame the system also, as implementing template for C++ (also C++ in
general) is very difficult job for compiler writers, as the language is
very ambiguous from compiler writer's perspective, esp template (I have
enough experience from my past job :) ) .Thus it is not strange that
they don't implement many of the standard features.
The popular frameworks like wxWidgets or Qt don't support template
mostly because, if they do so, the supported platform will get reduced
to less than half of what they do now.
The second problem is the kind of generic programming template offers
is somewhat different than OO generics. Many prefer single rooted
object hierarchy rather than template meta-programming (like most of
the existing frameworks).
The problem with template is that it do not respect object hierarchy
(unlike Java generics) .Thus one can write,
XYZFile button = window.createWidget<XYZFile>("OK");
Compiler will happily accept it if it found a matched ctor, or matched
methods which are called. But the whole system will behave abnormally,
as XYZFile know how to paint in a file, not in a window!
Instead, window.addWidget(Widget& ) or window.addWidget(Window* )
respect object hierarchy, and dont have such problem.
 
R

Ron Natalie

Tommo said:
1. Not true. Objects created with new are created on the heap, all
other are on the stack. You may want some objects to live in ( passed
your immediate scope usage ) and so you would use new

Not true. You've forgotten about static allocation of objects.
This is a third category of storage as far as the language is
concerned. On many machines this is the base of the free
store area but that's an implementation detail. I've never
come across an implementation where it was in the stack
allocation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,998
Latest member
MarissaEub

Latest Threads

Top