473,658 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

realloc vs vector

I've got an array in the vein of

MyType* array;
arry = new MyType[100];

This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'.

So, if I used std :: vector in order to resize `array', both lists of
pointers would contain garbage, given the resize operation of the
container would shift the memory around - something which I can hardly
check statically.

So what is a good way of dynamically resizing an array without having
to rearrange the internal memory representation? Or, am I on the
totally wrong track here... (might well be). I thought of using
malloc and realloc, but then these do not call the constructors and
destructors of MyType.

Andi.
Jul 22 '05 #1
6 5299

"Andreas Bauer" <ba*****@mailbr oy.informatik.t u-muenchen.de> wrote in
message news:sl******** ************@lo calhost.localdo main...
I've got an array in the vein of

MyType* array;
arry = new MyType[100];

This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'.

So, if I used std :: vector in order to resize `array', both lists of
pointers would contain garbage, given the resize operation of the
container would shift the memory around - something which I can hardly
check statically.

So what is a good way of dynamically resizing an array without having
to rearrange the internal memory representation? Or, am I on the
totally wrong track here... (might well be). I thought of using
malloc and realloc, but then these do not call the constructors and
destructors of MyType.

Andi.


The answer is very simple, don't keep pointers to the 'array'. This will
cause problem whatever means of resizing the array you use, malloc/realloc,
new, vector, its all the same.

Instead keep integer indexes in your lists, these will always be valid.

john
Jul 22 '05 #2

"Andreas Bauer" <ba*****@mailbr oy.informatik.t u-muenchen.de> schrieb im
Newsbeitrag news:sl******** ************@lo calhost.localdo main...
I've got an array in the vein of

MyType* array;
arry = new MyType[100];
So, if I used std :: vector in order to resize `array', both lists of
pointers would contain garbage, given the resize operation of the
container would shift the memory around - something which I can hardly
check statically.


You could use a std::deque, where references to items are not invalid after
a growth.
Of course a deque is not an dynamic array its more a dynamic array of
pointers to the stored elements.
(Thats why the references to items can stay valid during growth)
Regards
Michael
Jul 22 '05 #3
"Andreas Bauer" <ba*****@mailbr oy.informatik.t u-muenchen.de> wrote in
message news:sl******** ************@lo calhost.localdo main...
I've got an array in the vein of MyType* array;
arry = new MyType[100]; This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'. So, if I used std :: vector in order to resize `array', both lists of
pointers would contain garbage, given the resize operation of the
container would shift the memory around - something which I can hardly
check statically. So what is a good way of dynamically resizing an array without having
to rearrange the internal memory representation? Or, am I on the
totally wrong track here... (might well be). I thought of using
malloc and realloc, but then these do not call the constructors and
destructors of MyType.


It wouldn't work anyway, because realloc would invalidate those pointers as
surely as std::vector would.

If you must have pointers to your container elements, rather than integers
that represent array indices, have you considered std::deque instead? It
has the property of not moving elements around as long as you restrict
yourself to inserting and deleting elements at either end of the sequence,
rather than in the middle.
Jul 22 '05 #4
"Andreas Bauer" <ba*****@mailbr oy.informatik.t u-muenchen.de> wrote in
message
MyType* array;
arry = new MyType[100];

This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'.
In addition to std::deque as others pointed out, you can also try std::list.
This one lets you insert elements even in the middle of the list, and
pointers to existing elements remain valid!

So what is a good way of dynamically resizing an array without having
to rearrange the internal memory representation? Or, am I on the
totally wrong track here... (might well be). I thought of using
malloc and realloc, but then these do not call the constructors and
destructors of MyType.


Note that realloc is not garaunteed to work. If the array can be grown in
place, that is if the memory is available, then yes it will work (ie.
pointers to existing elements will remain valid). But if no space is
available, realloc does a malloc and copies elements from the old place to
the new. Besides, you can only use malloc etc with POD types (or just
bytes).
Jul 22 '05 #5
"John Harrison" <jo************ *@hotmail.com> wrote in message
"Andreas Bauer" <ba*****@mailbr oy.informatik.t u-muenchen.de> wrote in
MyType* array;
= new MyType[100];

This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'.

The answer is very simple, don't keep pointers to the 'array'. This will
cause problem whatever means of resizing the array you use, malloc/realloc, new, vector, its all the same.

Instead keep integer indexes in your lists, these will always be valid.


A very good solution too.

But what if the array of pointers has pointers to objects from different
array's? Then keeping the index is not enough. You need a struct that
contains a pointer to the array as well as an integer index.
Jul 22 '05 #6
Andreas Bauer wrote:
I've got an array in the vein of

MyType* array;
arry = new MyType[100];

This of course works fine, but I have the need to dynamically grow the
boundaries of that array at runtime. I can't seem to use std ::
vector or any other container, cause I've got two more "lists" which
keep pointers to the elements of `array'.

So, if I used std :: vector in order to resize `array', both lists of
pointers would contain garbage, given the resize operation of the
container would shift the memory around - something which I can hardly
check statically.

So what is a good way of dynamically resizing an array without having
to rearrange the internal memory representation? Or, am I on the
totally wrong track here... (might well be). I thought of using
malloc and realloc, but then these do not call the constructors and
destructors of MyType.

You can use vector::reserve () to reserve memory (but no objects get
created) for future expansion:
#include <vector>
int main()
{
using std::vector;
vector<int>some Vec;

// Reserves memory for 500 objects.
// Future expansion up to this number
// guarantees that no objects will be moved
// No objects get created
someVec.reserve (500);
// Other operations
// ...

someVec.resize( 100);

// ...
}

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #7

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

Similar topics

8
6911
by: Bren | last post by:
Can anybody tell me what is wrong with this code? void SystemModule::AddModuleDependency(PTR_MODULE_INFO pModuleInfo) { if (!pModuleInfo) return; PTR_MODULE_INFO pDest = 0; if (!m_pDependencies)
1
6326
by: Henrik J | last post by:
Hello group... I have this little problem: I'm using a struct **foo. I have allocated x foo's using malloc: foo=(FOO**)malloc(Amount*sizeof(FOO*)); No problem....!
2
2085
by: DrBob | last post by:
gcc 3.3 on Mac OS X. I need to dynamically grow a buffer by concatinating raw binary data in chunks. How do I use 'new' to grow the buffer size as its contents grow? I know this can be done with realloc.. (realloc will give you a new pointer to a new buffer that has the same contents as the previous buffer and will free the previous buffer for you).
18
555
by: Kumar | last post by:
Hi, Can somebody advise me on what is the best alternative for realloc in C++? Is it safe to "realloc"ate memory allocated using new operator ?
12
2931
by: Michael | last post by:
How would I go about shrinking the buffer that was allocated with new, or expanding it in place? I basically need a realloc equivalent for new. Thanks in advance. Michael
86
4118
by: Walter Roberson | last post by:
If realloc() finds it necessary to move the memory block, then does it free() the previously allocated block? The C89 standard has some reference to undefined behaviour if one realloc()'s memory that was freed by realloc(), but the only way explicitly mentioned in the C89 standard to free memory via realloc() is to realloc() it down to 0 bytes. I had always assumed it would automatically free the previous memory, but is the behaviour...
5
2984
by: matt.wolinsky | last post by:
Hello C++ gurus, I am trying to learn about how to use C++ memory management, and I know that there is no "renew" command in C++. What I am hoping to do is slightly different though. I want to implement a dynamic "array" by using an array of pointers to objects,
8
7344
by: barcaroller | last post by:
Does C++ have an equivalent to C's realloc() that can be safely used with C++'s new and delete. If not, what is the proper way to resize memory blocks in C++ (other than using malloc/realloc/free)?
1
4913
by: Richard Harter | last post by:
On Fri, 27 Jun 2008 09:28:56 -0700 (PDT), pereges <Broli00@gmail.comwrote: There are some obvious questions that should be asked, e.g., is the contents of your array already sorted as your example implies. If they are then all you need to do is find the element at index k = n/2 and then increase k until you find an element that differs from A. Then k is the number of left children and n-k is the number of right children. (Fencepost...
0
8427
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
8330
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
8850
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
8626
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
7355
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
5649
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
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2749
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
2
1737
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.