473,668 Members | 2,486 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Deallocating Individual Elements of an Array Allocated Using new[]

I need to be able to allocate large numbers of elements at a time but
then delete them one at a time. I have settled on the design of using
new[] to allocate many items at once, but am unsure what is legal/
illegal about deallocation. Here's an example of what I would like to
do:
int *x = new int[1000];
....
delete x;
....
delete x+1;
....
delete x+2;
....
....
delete x+999;
Can I do this? Or do I have to delete the entire allocated array in
one chunk using delete[]? This example is not entirely accurate as I
would like the ordering of deletes to be more or less arbitrary. Any
help is greatly appreciated. Thanks,
-Chris
PS - If you want to know why I want this done - it's because I want to
save time allocating many objects instead of just one at a time and
I'll be passing pointers to these objects to many different functions
and places which will use them for awhile and then want to be able to
delete them.

Jun 5 '07 #1
8 4104
Chris Portka <ch*********@gm ail.comwrote in
news:11******** **************@ o11g2000prd.goo glegroups.com:
I need to be able to allocate large numbers of elements at a time but
then delete them one at a time. I have settled on the design of using
new[] to allocate many items at once, but am unsure what is legal/
illegal about deallocation. Here's an example of what I would like to
What you new[], you must delete[]. What you new you must delete. Never
mix them.
do:
int *x = new int[1000];
...
delete x;
...
delete x+1;
...
delete x+2;
...
...
delete x+999;
Can I do this? Or do I have to delete the entire allocated array in
one chunk using delete[]? This example is not entirely accurate as I
One chunk, using delete[]. You new[]'ed it, you delete[] it.
would like the ordering of deletes to be more or less arbitrary. Any
help is greatly appreciated. Thanks,
-Chris
PS - If you want to know why I want this done - it's because I want to
save time allocating many objects instead of just one at a time and
I'll be passing pointers to these objects to many different functions
and places which will use them for awhile and then want to be able to
delete them.

Jun 5 '07 #2
On Jun 5, 3:40 pm, Chris Portka <chrispor...@gm ail.comwrote:
I need to be able to allocate large numbers of elements at a time but
then delete them one at a time. I have settled on the design of using
new[] to allocate many items at once, but am unsure what is legal/
illegal about deallocation. Here's an example of what I would like to
do:
int *x = new int[1000];
...
delete x;
...
delete x+1;
...
delete x+2;
...
...
delete x+999;
Can I do this? Or do I have to delete the entire allocated array in
one chunk using delete[]? This example is not entirely accurate as I
would like the ordering of deletes to be more or less arbitrary. Any
help is greatly appreciated. Thanks,
-Chris

PS - If you want to know why I want this done - it's because I want to
save time allocating many objects instead of just one at a time and
I'll be passing pointers to these objects to many different functions
and places which will use them for awhile and then want to be able to
delete them.
Hello, Chris.

You can't deallocate memory that you don't allocate. In other words,
you can only deallocate memory using delete for the pointers you
receive from new calls. If you need to dealocate one by one object,
you will need to allocate one by one object:

typedef int* PInt;
PInt* px = new PInt[1000];
for( size_t i = 0; i < 1000; ++i )
px[i] = new int();

....
delete px[0];
....
delete px[1];
....
delete px[2];
....
....
delete px[999];

Now, if you can use STL instead pure and primitive arrays, we can use
a list:

std::list<intx( 1000);
....
x.erase(myItera tor);
....
x.erase(myItera tor2);
....
....
x.erase(myItera tor999);

If I understood your target, and think the best method for what you
looking for would be to use the placement new, i.e., creating all the
objects you need inside a preallocated area of memory. After that,
instead of deallocating the memory, you just need to call the
destructor for the objects you need to dismiss. I assuming you using
this technique with a real object, not primitive types. So:

unsigned char myMem[sizeof(MyClass) * 1000);
MyClass* pMyObjects = new (myMem) MyClass[1000];
....
pMyObjects[0].~MyClass();
....
pMyObjects[1].~MyClass();
....
pMyObjects[2].~MyClass();
....
....
pMyObjects[999].~MyClass();

[]s

Wanderley Caloni
=============== =======
http://www.cthings.org

Jun 5 '07 #3
If I understood your target, and think the best method for what you
looking for would be to use the placement new, i.e., creating all the
objects you need inside a preallocated area of memory. After that,
instead of deallocating the memory, you just need to call the
destructor for the objects you need to dismiss. I assuming you using
this technique with a real object, not primitive types.
Yes, you are correct and this was my intuition - preallocating memory
somehow. However I'm slightly confused by your suggestion to just
call the destructor for objects I need to dismiss. I thought that
calling the destructor does not actually free the memory associated
with the object - my understanding is that delete gets transformed as
such:
delete obj; --compiles to...
if (obj != NULL) {
obj->~Object();
operator delete(obj);
}
So if the destructor doesn't free anything, then I have to explicitly
free the preallocated memory array anyway - why waste time calling the
destructor when I can just call delete[] for the entire array? The
overall goal is to avoid an additional messy data structure that would
have to keep track of all the new[]'s for preallocated memory, detect
when all the objects were finished, and safely call delete[] for the
preallocated memory. It looks as though C++ does not offer a way to
avoid this unless what you're saying about the destructor actually
frees the memory from the preallocated array.
>
unsigned char myMem[sizeof(MyClass) * 1000);
MyClass* pMyObjects = new (myMem) MyClass[1000];
...
pMyObjects[0].~MyClass();
...
pMyObjects[1].~MyClass();
...
pMyObjects[2].~MyClass();
...
...
pMyObjects[999].~MyClass();

[]s
Jun 5 '07 #4
On 2007-06-05 20:40, Chris Portka wrote:
I need to be able to allocate large numbers of elements at a time but
then delete them one at a time. I have settled on the design of using
new[] to allocate many items at once, but am unsure what is legal/
illegal about deallocation. Here's an example of what I would like to
do:
int *x = new int[1000];
...
delete x;
...
delete x+1;
...
delete x+2;
...
...
delete x+999;
Can I do this? Or do I have to delete the entire allocated array in
one chunk using delete[]? This example is not entirely accurate as I
would like the ordering of deletes to be more or less arbitrary. Any
help is greatly appreciated. Thanks,
-Chris
PS - If you want to know why I want this done - it's because I want to
save time allocating many objects instead of just one at a time and
I'll be passing pointers to these objects to many different functions
and places which will use them for awhile and then want to be able to
delete them.
Is there any special reason why you can't wait and deallocate them all
at once? Even if you could deallocate using delete what you allocated
with new[] you would probably not be able to reallocate in the same area
of memory until all of them had been deallocated so I can't see any gain
from not deallocating them all at once.

--
Erik Wikström
Jun 5 '07 #5
On Jun 5, 4:49 pm, Chris Portka <chrispor...@gm ail.comwrote:
Yes, you are correct and this was my intuition - preallocating memory
somehow. However I'm slightly confused by your suggestion to just
call the destructor for objects I need to dismiss. I thought that
calling the destructor does not actually free the memory associated
with the object - my understanding is that delete gets transformed as
such:
delete obj; --compiles to...
if (obj != NULL) {
obj->~Object();
operator delete(obj);}
Quite right. My suggestion is explained by the fact that I thought
your main concern was related with the destruction of objects, not the
memory management. In this case, the deallocation would only take
place at the end of use of all elements inside the collection, but you
would be able to destruct any objects inside this array.
So if the destructor doesn't free anything, then I have to explicitly
free the preallocated memory array anyway - why waste time calling the
destructor when I can just call delete[] for the entire array? The
overall goal is to avoid an additional messy data structure that would
have to keep track of all the new[]'s for preallocated memory, detect
when all the objects were finished, and safely call delete[] for the
preallocated memory. It looks as though C++ does not offer a way to
avoid this unless what you're saying about the destructor actually
frees the memory from the preallocated array.
Now, back to the memory problem, I recommend the use of STL list
class, if you want a collection of structures and don't want to worry
about how to manage the deallocation of each element inside it, and
these elements can be deallocated in a random way.

[]s

Wanderley Caloni
=============== =======
http://www.cthings.org

Jun 5 '07 #6
Is there any special reason why you can't wait and deallocate them all
at once? Even if you could deallocate using delete what you allocated
with new[] you would probably not be able to reallocate in the same area
of memory until all of them had been deallocated so I can't see any gain
from not deallocating them all at once.
Yes there is a special reason, as I mentioned in my second comment -
if I were to delete them all at once, this would require knowing when
it was safe to delete them all. In order to know this I would have to
keep around another data structure that kept track of which objects
were finished and once it detected they were all finished, I could
delete them. I'm trying to avoid using any additional data
structures.
-Chris

Jun 5 '07 #7
On Jun 5, 1:35 pm, Chris Portka <chrispor...@gm ail.comwrote:
Is there any special reason why you can't wait and deallocate them all
at once? Even if you could deallocate using delete what you allocated
with new[] you would probably not be able to reallocate in the same area
of memory until all of them had been deallocated so I can't see any gain
from not deallocating them all at once.

Yes there is a special reason, as I mentioned in my second comment -
if I were to delete them all at once, this would require knowing when
it was safe to delete them all. In order to know this I would have to
keep around another data structure that kept track of which objects
were finished and once it detected they were all finished, I could
delete them. I'm trying to avoid using any additional data
structures.
-Chris
You may want to consider using vectors to store the pointers.

Jun 5 '07 #8
On 5 Jun., 22:35, Chris Portka <chrispor...@gm ail.comwrote:
Is there any special reason why you can't wait and deallocate them all
at once? Even if you could deallocate using delete what you allocated
with new[] you would probably not be able to reallocate in the same area
of memory until all of them had been deallocated so I can't see any gain
from not deallocating them all at once.

Yes there is a special reason, as I mentioned in my second comment -
if I were to delete them all at once, this would require knowing when
it was safe to delete them all. In order to know this I would have to
keep around another data structure that kept track of which objects
were finished and once it detected they were all finished, I could
delete them. I'm trying to avoid using any additional data
structures.
-Chris
When you allocate something with new[], it results in ONE big chunk of
memory. You can't deallocate a part of this chunk, only the full
chunk. If you allocate the same amount of objects with several new (no
[]!) calls, it results in multiply memory chunks, which can be deleted
separately.

If it is your target to safe the allocation/deallocation time, use a
memory pooling library (for example boost::pool). If it is your target
to safe memory, use a std::list, as already suggested before.

Jun 5 '07 #9

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

Similar topics

8
2203
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the destructor on the element is invoked. I wonder why it has to be this way. In my opinion, this renders...
27
4211
by: Daniel Lidström | last post by:
Hello! I want to work with individual bytes of integers. I know that ints are 32-bit and will always be. Sometimes I want to work with the entire 32-bits, and other times I want to modify just the first 8-bits for example. For me, I think it would be best if I can declare the 32-bits like this: unsigned char bits;
34
4164
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want to assign a pointer contained in an exisiting instance of a Class B to this
11
4456
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to accomplish. // - - - - - - - - begin code - - - - - - - typedef int sm_t; typedef int bg_t; sm_t sm; bg_t bg;
13
3598
by: lovecreatesbeauty | last post by:
/* How do free() know how many elements should be freed in a dynamic array? When free a single variable, the amount of byte of memory can be retrieved from the type of variable itself. Now, suppose there is an array of more than one element need to be freed, as free() doesn't accept a argument indicating the size, how can
4
2777
by: vaiism | last post by:
I am trying to write a string compare function using pointers and dynamic arrays, and am having trouble comparing the individual elements of the array contained with the struct. The code below works, but I was wondering if there was a way to use pointers instead of the index in the last for loops to compare the individual components of the char array contained in the struct? (I also have code to determine the size of the char array, dependent...
4
4596
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the length of my queue. I started getting compilation errors when I included a length function. <code> template<class ItemType> void Queue<ItemType>::MakeEmpty() {
6
1795
by: Amit_Basnak | last post by:
Dear Friends I have two structures as below typedef struct { long_int length; char data; } CI_STRUCT_DATA; typedef CI_STRUCT_DATA *ptr_CiStructData;
11
7691
by: C C++ C++ | last post by:
Hi all, got this interview question please respond. How can you quickly find the number of elements stored in a a) static array b) dynamic array ? Rgrds MA
0
8462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8381
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
8799
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
8586
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
8658
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
7401
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
6209
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
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2026
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.