473,323 Members | 1,550 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

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 1911

<Pe*********@gmail.comwrote in message
news:11**********************@u36g2000prd.googlegr oups.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*********@gmail.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...@gmail.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 objektorientierter Datenverarbeitung
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...@gmail.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...@gmail.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*********@gmail.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
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...
20
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...
62
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();...
66
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...
33
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...
1
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...
66
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
3
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'...
19
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.