473,803 Members | 3,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why using the new keyword at all for memory allocation?

Why using the new keyword at all for memory allocation?

I mean,why not let c++ find memory for you variable automatically?

so insted of :

int proba;
proba = new int[5];

why not just :

int proba[5];

????????????

May 23 '07 #1
6 1927

<Pe*********@gm ail.comwrote in message
news:11******** **************@ u36g2000prd.goo glegroups.com.. .
Why using the new keyword at all for memory allocation?

I mean,why not let c++ find memory for you variable automatically?

so insted of :

int proba;
proba = new int[5];

why not just :

int proba[5];
Well, that's the preferred way to do it, assuming you know at compile time
how much memory you'll need to allocate. But what if you don't? How do you
allocate a memory chunk if you don't know until run-time how much memory you
need?

There are also times when you allocate one new object at a time, in response
to some sort of event, and add the new'ed pointer to a container which
handles its objects over their lifetime.

There are ways around using new even in these cases (such as a "pool"), but
those are generally used to solve observed problems with dynamic allocation
in very specific cases.

You might also look into "smart pointers", which can make life much easier
on you when it comes to maintaining dynamically-allocated objects.

-Howard


May 23 '07 #2
Pe*********@gma il.com wrote:
Why using the new keyword at all for memory allocation?
Several reasons. Lifetime control, for one. Dynamic sizing.
Free store usually has more room than the place where automatic
variables live.
I mean,why not let c++ find memory for you variable automatically?

so insted of :

int proba;
proba = new int[5];
Actually it's more like

int *proba = new int[5];
>
why not just :

int proba[5];

????????????
In many cases, if all you need is an array of _exactly_ 5 integers,
and it is only needed in this particular scope, that's how you'd do
it. However, if the size is only known at the run-time, you are
either stuck with an array that is large enough to accommodate any
needed size (which means wasting memory in many cases) or got to do
dynamic allocation.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
May 23 '07 #3
On May 23, 8:28 pm, PencoOdS...@gma il.com wrote:
Why using the new keyword at all for memory allocation?
I mean,why not let c++ find memory for you variable automatically?
so insted of :
int proba;
proba = new int[5];
why not just :
int proba[5];
????????????
Lifetime.

First, of course, you'd never write the former; it won't even
compile. There are cases where the second might be used, when
you know the exact size of the array, and it is a compile time
constant, but something like:
std::vector< int proba( 5 ) ;
is much more frequent and useful. (And I can't think of a case
where you'd ever use "new int[5]".)

But both the first and the second have automatic storage
duration if they are declared as local variables, and static
storage duration if they are declared at namespace scope (or if
you add the specifier "static" before the declaration of a local
variable). Automatic storage duration follows scope; the
variable ceases to exist when you leave the scope in which it
was defined. And static storage duration is the lifetime of the
program. If this doesn't match the requirements, you have to
manage lifetime yourself, manually, which means new and delete,
e.g.:

std::vector< int >* proba = NULL ;
// ...
proba = new std::vector< int >( 5 ) ;
// ...
delete proba ;

While this occurs very, very rarely for more or less basic
types, like int or vector, it is the usual case for entity
objects.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 24 '07 #4
Kar
Actually C++ find memory at three different places.

1.stack
2.heap
3.free-store

In stack :any thing without new key word here { int proba[5]; }
In free-store : use as you mentioned
In heap : use malloc funtion

Wishes
Kar
On May 23, 11:28 pm, PencoOdS...@gma il.com wrote:
Why using the new keyword at all for memory allocation?

I mean,why not let c++ find memory for you variable automatically?

so insted of :

int proba;
proba = new int[5];

why not just :

int proba[5];

????????????

May 24 '07 #5
On 24 May, 12:10, Kar <karmegamem...@ gmail.comwrote:

Please don't top-post. Thank you. Rearranged.
On May 23, 11:28 pm, PencoOdS...@gma il.com wrote:
Why using the new keyword at all for memory allocation?
I mean,why not let c++ find memory for you variable automatically?
so insted of :
int proba;
proba = new int[5];
why not just :
int proba[5];

Actually C++ find memory at three different places.

1.stack
2.heap
3.free-store
Actually, C++ finds memory in one place - the computer on which the
program is running. There are however three different types of
*storage duration* that C++ defines.

1. Automatic storage duration (which is almost certainly what you are
referring to as "stack").
2. Dynamic storage duration (which is almost certainly what you are
referring to as "heap" and "free-store").
3. Static storage duration (which you missed out).
In stack :any thing without new key word here { int proba[5]; }
In free-store : use as you mentioned
In heap : use malloc funtion
That's not correct.

In terms of storage duration there is no distinction between new and
malloc. Objects that live in memory allocated via new or via malloc
will have dynamic storage duration.

Objects defined at namespace scope or with the static storage modifier
will have static storage duration.

Anything else will have automatic storage duration.

Gavin Deane

May 24 '07 #6
Pe*********@gma il.com wrote:
Why using the new keyword at all for memory allocation?

I mean,why not let c++ find memory for you variable automatically?

so insted of :

int proba;
proba = new int[5];

why not just :

int proba[5];

????????????
If think what the poster is trying to ask is why we should need to care about
memory allocations at all. Consider MatLab for example. There you can use any
identifier like an matrix without having to specify the dimensions beforehand,
and the interpreter will automatically allocate space if you assign an element
that lies outside the currently allocated space.

Similiar behaviour can be found in std::vector, for instance (the vector can
grow dynamically, so you don't have to know its size at compile time). You
should keep in mind, that such data structures like std::vector can cause severe
performance penalties if used careless (the standard example of careless use of
dynamically growing data structures is when you add one element at a time to a
CString from MFC 6.0. Each time you do this the underlying buffer must be
re-allocated and copied!)

Regards,
Stuart
May 25 '07 #7

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

Similar topics

6
8214
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, 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 : DestinationAddress* dest = new DestinationAddress(); // code 1
20
3504
by: Sushil | last post by:
Hi gurus I was reading FAQ "alloca cannot be written portably, and is difficult to implement on machines without a conventional stack." I understand that the standard does not mandate "heap" or "stack" I'm curious to know the implemenations which dont have stack or heap.
62
17865
by: ivan.leben | last post by:
How can I really delete a preloaded image from memory/disk cache? Let's say I preload an image by creating an Image object and setting its src attribute to desired URL: var img = new Image(); img.src = ; Then I use the image a few more times by adding it into an Array object:
66
3647
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
33
3295
by: Snis Pilbor | last post by:
With the "as if" rule in play, doesn't that effectively render the "register" keyword completely useless? Example: I make a silly compiler which creates code that goes out of its way to take a full 10 minutes every time a "register" declared variable is read from or written to. Besides this lag, everything else runs as expected. Then my compiler is still C compliant, aye? If so, then it is unwise for any programmer to ever use the...
1
7979
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
66
3715
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
3
3238
by: not_a_commie | last post by:
The CLR won't garbage collect until it needs to. You should see the memory usage climb for some time before stabilizing. Can you change your declaration to use the 'out' keyword rather than a 'ref' keyword?
19
3401
by: =?ISO-8859-1?Q?Nordl=F6w?= | last post by:
I am currently designing a synchronized queue used to communicate between threads. Is the code given below a good solution? Am I using mutex lock/unlock more than needed? Are there any resources out there on the Internet on how to design *thread-safe* *efficient* data- structures? /Nordlöw
0
9564
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
10546
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
10310
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...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9121
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...
0
5498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.