473,839 Members | 1,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is the difference between dynamic memory allocation,and stack allocation ?


Hi all,

I need to know, what is the difference between dynamic memory
allocation, and stack allocation ?
1. If I have a class named DestinationAddr ess, when should I use
dynamic memory allocation to create object of that class ?
2. If it says "dynamic memory allocation", is it mean the
following code :
DestinationAddr ess* dest = new DestinationAddr ess(); // code 1

doesn't allocate address when compile time, but in run time ?

So, the following code :
DestinationAddr ess dest; // code 2

does allocate memory when compile time ?

3. In Java programming language, all object created on heap,
just like dynamic memory allocation on C++. So, why should
I use non-dynamic memory allocation just like on code 2 ?

Thanks in advance

Oct 27 '05 #1
6 8216
code 2 is faster than code 1.

Oct 27 '05 #2

chris skrev:
Hi all,

I need to know, what is the difference between dynamic memory
allocation, and stack allocation ?
1. If I have a class named DestinationAddr ess, when should I use
dynamic memory allocation to create object of that class ? Dynamic allocation allows you to create an object and return it. It
also allows you to not have any object at all. Finally, dynamic
allocation allows you to determine the type of the object at run-time.
If you need to use any of these features, you should use dynamic
allocation.
Stack allocation is faster and ensures automatic destruction when you
leave scope. You should normally prefer this if you can. An exception
could be if you use huge C-style arrays or otherwise have an object
that requires vast amounts of storage, but that would be an extreme
case in a normal system. 2. If it says "dynamic memory allocation", is it mean the
following code :
DestinationAddr ess* dest = new DestinationAddr ess(); // code 1

doesn't allocate address when compile time, but in run time ?
Correct.
So, the following code :
DestinationAddr ess dest; // code 2

does allocate memory when compile time ? Well, not actually. But the "allocation " is made for all local object
at entry to the function and the prize for this allocation is so low
that you can ignore the cost (at least on all architectures I'm aware
of).
3. In Java programming language, all object created on heap,
just like dynamic memory allocation on C++. So, why should
I use non-dynamic memory allocation just like on code 2 ?
Because you care about perfomance and ease of programming. Java is an
entirely different language where a garbage collecter takes care of
releasing your memory. In C++ there is (by default) no garbage
collection so you're on your own. In return C++ gives you deterministic
destruction on all objects and this is in my opinion far more valuable
(it is also one reason why C++ does not need finally).
Thanks in advance


/Peter

Oct 27 '05 #3

peter koch wrote:
chris skrev:

3. In Java programming language, all object created on heap,
just like dynamic memory allocation on C++. So, why should
I use non-dynamic memory allocation just like on code 2 ?


Because you care about perfomance and ease of programming. Java is an
entirely different language where a garbage collecter takes care of
releasing your memory. In C++ there is (by default) no garbage
collection so you're on your own. In return C++ gives you deterministic
destruction on all objects and this is in my opinion far more valuable
(it is also one reason why C++ does not need finally).


Just to add to this for the OP, on those occasions where you need
dynamic storage duration, you are indeed on your own. By which I mean
that _you_ are responsible for paring every new with a delete and every
new[] with a delete[] to avoid leaking memory.

Wrap ALL you dynamic allocations in smart pointers (e.g. std::auto_ptr
or something from the boost smart pointers library) or other class
constructors and you will find this responsibility much less onerous.

Gavin Deane

Oct 27 '05 #4
chris wrote:
Hi all,

I need to know, what is the difference between dynamic memory
allocation, and stack allocation ?
The main difference is that with dynamic allocation you get to choose
when the object is destroyed. Dynamically allocated objects are
destroyed only when you explicitly delete them.
1. If I have a class named DestinationAddr ess, when should I use
dynamic memory allocation to create object of that class ?
The main thing to consider is whether you want to control when the
object is destroyed.
2. If it says "dynamic memory allocation", is it mean the
following code :
DestinationAddr ess* dest = new DestinationAddr ess(); // code 1

doesn't allocate address when compile time, but in run time ?
Run time.

So, the following code :
DestinationAddr ess dest; // code 2

does allocate memory when compile time ?
Run time also.

As already said the main difference is not when the memory is allocated
but when the object is destroyed.

3. In Java programming language, all object created on heap,
just like dynamic memory allocation on C++. So, why should
I use non-dynamic memory allocation just like on code 2 ?

Because you don't have to remember to delete the object. Because you are
happy with the idea that the object will be destroyed when the variable
goes out of scope. Most of the time that is what you want and that is
what stack allocation gives you.
Thanks in advance


john
Oct 27 '05 #5
Ayoung Chueng wrote:
code 2 is faster than code 1.

That isn't necessarily true.

The big difference, is that you know the lifetime of the object will be
automatically ended wherever that variable in #2 exits. In the case
of a dynamic allocation you must make sure that you specifically delete
the object.
Oct 27 '05 #6

peter koch wrote:
Dynamic allocation allows you to create an object and return it. It
Peter, what did you mean by "return it" above ?
also allows you to not have any object at all. Finally, dynamic
and what did you mean by "to not have any object at all" ? Did you
mean, I just create unitialized pointer, like this :

DestinationAddr ess *pDestAddress;

allocation allows you to determine the type of the object at run-time.
If you need to use any of these features, you should use dynamic
allocation.
Stack allocation is faster and ensures automatic destruction when you
leave scope. You should normally prefer this if you can. An exception


and what did you mean by "leave scope" ? When is stack allocation
destructed automatically ? If I pass an stack-allocated object by
reference to other class, how do I know when it will be destroyed ?

Oct 28 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
3645
by: wwj | last post by:
Hi ,all I want to know the difference between char a and char *p=new char and the difference between the heap and the stack ,and if the char a is corresponding to the stack in MEMORY,and char *p=new char is corresponding to the heap of MEMORY. Give me some hint. THANK YOU.
5
7020
by: bull | last post by:
hi could any one explain with example the following in a better way to understand 1. what is stack in memory, how the programs are stored in stack , what is the use of stack 2. What is heap in memory, how the programs are stored in heap , what is the use of heap 3. what is pool memory otherwise memory pool, what is the use of memory pool 4. what is difference between stack and heap
2
13752
by: Ma Xiaoming | last post by:
Dear ladies and gentlemen, I don't understand what the difference between the Heap and the Stack is. Could you please explain the difference between the both for me? Thank you very much. Best regards.
28
4656
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
61
3166
by: academic | last post by:
When I declare a reference variable I initialize it to Nothing. Now I'm wondering if that best for String variables - is "" better? With Nothing I assume no memory is set aside nor GC'ed But with "" it is - correct? The system seems to handle a null the same as "".
7
2811
by: Michael | last post by:
Hi, What's the benefit to dynamically allocate memory? using namespace std; int main() { char* ptr; ptr="abc";
11
3068
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
12
2394
by: contactmayankjain | last post by:
Hi, Its said that one should avoid dynamic allocation of memory, as it de- fragment the memory into small chunks and allocation of memory is a costly process in terms of efficiency. So what is the best solution to handle to situation in which we need to allocate memory at run time. Regards Mayank Jain(Nawal)
14
3842
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
0
9697
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10908
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10587
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9426
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7829
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7018
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3136
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.