473,968 Members | 21,035 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Realloc array of pointers to objects?

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,
something like this:

class Element { double a,b,c; };

struct ElementArray { int Nel,Nall; Element **els; };

void InsertElement(E lementArray &A,Element El)
{
if( A.Nel == A.Nall )
{ A.Nall+=10; // some block size
A.els = (Element**)real loc(A.els,A.Nal l*sizeof(Elemen t*));
for(int el=A.Nel; el<A.Nall;lyr++ ) A.els[el] = new Element;
}
*A.els[A.Nel]=El;
A.Nel++;

}

Will this work? (I know I haven't checked for successful memory
allocation)

I am not moving El objects around, but I am moving around pointers
returned by new.
Will this create problems?

I have started on a program using this approach, and am getting some
errors, but I don't
know if this is because of my use of realloc.

I would appreciate any advice you may have.

Thank you for your assistance,

Matt Wolinsky

May 18 '06 #1
5 3003
ma***********@g mail.com wrote:
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,
something like this:


Don't roll your own. Use std::vector for dynamic arrays. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-34.1

If you need to allocate memory dynamically, prefer new/delete to
malloc/realloc/free. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-16.4

Cheers! --M

May 18 '06 #2

mlimber wrote:

Don't roll your own. Use std::vector for dynamic arrays. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-34.1

If you need to allocate memory dynamically, prefer new/delete to
malloc/realloc/free. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-16.4

Cheers! --M


I know, I know, I must learn to trust the C++ way.

Can you specify a "realloc block size" to use with std::vector, so it
doesn't
have to allocate a new element each time it grows? My main interest is
in having
a dynamic "stack" of objects, but I will sometimes need to access
neighboring elements and/or march through the whole stack sequentially.
BTW I did get the pseudocode in my earlier post to work (or at least
not crash on the inputs I was using).

My increment function was

void InsertElement(E lementArray &A,Element El);

I found stepping through the debugger that for some reason El was being
treated as
a pointer! (i.e. El[0] gave me the object contents I expected, while El
was an address).

Changing my increment function to

void InsertElement(E lementArray &A,Element &El)

appears to have fixed the difficulty!

I have no idea why this is the case. I guess I have a lot to learn
about C++.

May 18 '06 #3
On Thu, 18 May 2006 12:29:52 -0700, "matt.wolin sky wrote:
mlimber wrote:

Don't roll your own. Use std::vector for dynamic arrays. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-34.1

If you need to allocate memory dynamically, prefer new/delete to
malloc/realloc/free. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-16.4

Cheers! --M


I know, I know, I must learn to trust the C++ way.

Can you specify a "realloc block size" to use with std::vector, so it
doesn't
have to allocate a new element each time it grows? My main interest is in
having
a dynamic "stack" of objects, but I will sometimes need to access
neighboring elements and/or march through the whole stack sequentially.


std::vector already does that.
May 18 '06 #4

ma***********@g mail.com wrote:
Can you specify a "realloc block size" to use with std::vector, so it
doesn't
have to allocate a new element each time it grows?


I assume you have already written your implementation, profiled, and
found a bottleneck at vector insertion.

You can do two things under such extremely rare conditions:

1) Specify a size in element count for the initial vector and/or
"resize" to a particular size.
2) Write a specialized allocator for your element types and pass it as
template parameter to the vector template.

The first is easy. The second requires knowledge I have not needed to
learn thus far.

May 18 '06 #5
ma***********@g mail.com wrote:
mlimber wrote:

Don't roll your own. Use std::vector for dynamic arrays. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-34.1

If you need to allocate memory dynamically, prefer new/delete to
malloc/realloc/free. See this FAQ:

http://www.parashift.com/c++-faq-lit....html#faq-16.4

Cheers! --M


I know, I know, I must learn to trust the C++ way.

Can you specify a "realloc block size" to use with std::vector, so it
doesn't
have to allocate a new element each time it grows? My main interest is
in having
a dynamic "stack" of objects, but I will sometimes need to access
neighboring elements and/or march through the whole stack sequentially.
BTW I did get the pseudocode in my earlier post to work (or at least
not crash on the inputs I was using).

My increment function was

void InsertElement(E lementArray &A,Element El);

I found stepping through the debugger that for some reason El was being
treated as
a pointer! (i.e. El[0] gave me the object contents I expected, while El
was an address).

Changing my increment function to

void InsertElement(E lementArray &A,Element &El)

appears to have fixed the difficulty!

I have no idea why this is the case. I guess I have a lot to learn
about C++.


I would suggest you pick up _Accelerated C++_ by Koenig and Moo. It
teaches C++ from the ground up the right way.

Cheers! --M

May 18 '06 #6

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

Similar topics

6
5321
by: Andreas Bauer | last post by:
I've got an array in the vein of MyType* array; arry = new MyType; 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'.
9
4043
by: WL | last post by:
Hey, all. I'm creating an array of strings (char **argv style) on the fly, and using realloc to create string pointers, and malloc for the strings itself (if that makes any sense). I'm using the construct ptr = realloc(ptr, size); *ptr = malloc(string_length); strncpy(ptr, src, string_length); to call realloc() multiple times. This should be ok, right?
9
4091
by: Goh, Yong Kwang | last post by:
I'm currently doing a project that has a array that supposed to be determined only at runtime. Originally, the prototype I did as a proof of theory (or a quick hack) So one method is to create a linked list and use malloc to create LinkedListNode as needed and use free() to destroy a node. But another easier way would be to use the realloc() function call to resize a memory block in the heap so that all the "nodes" are now consecutive...
4
4084
by: John | last post by:
I'm trying (struggling) to use realloc to grow a list of strings. The number of strings is not known (this is a subset of an assignment to write a recursive ls program... my BS was in EE, so I'm trying to catch up!). I'm working on the following program to try to figure this out. Now, I'm at the point where I'm filling up plines with (I belive) a list of pointers, each of which is pointing to a string ("foo 1", "foo 2", and so forth). ...
86
4234
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...
8
1945
by: Jean-Claude Arbaut | last post by:
When you realloc for more size, it may be necessary to allocate a new block, copy memory and deallocate the old, for example if there is not enough free space after the original block (maybe the only example ?). But, is it really necessary to _copy_ bytes ? When in a virtual memory environment (off-topic here, be I still think the question is worth), you don't access directly physical memory, but allocated pages, so would it be possible on...
64
8431
by: Robert Seacord | last post by:
The C standard doesn't say anything about what happens when you call realloc with a size argument of 0. Both glibc and openbsd appear to return a valid pointer to a zero-sized object.. e.g. the return of a malloc(0). Does anyone know of a runtime where realloc() free'ed the object and then returned NULL? If so, it would make the following idiom for realloc() exploitable. Here's the idiom, snagged from an openbsd man page: if ((p2 =...
6
2337
by: lithiumcat | last post by:
Hi, maybe you remember me, some time ago I asked about how to store an integer value into a void*, and I learned that doing pointer arithmetic yeilding a pointer outside of an object (except the one- after-last thingy) is undefined behaviour. Actually I was trying to associate a function pointer with a key, through an AVL tree that managed void* data. Function pointers can't be stored in void* (that is, the standard does not garantee...
35
5724
by: Bill Cunningham | last post by:
My string.h headers declares two functions I have been using called memfrob and strfry. They are encryption types functions. My man pages say they are standard to linux c and gnu c. They sure aren't in my C books. Interesting functions by they're OT here but this raises to me a question. If a function returns a pointer to a void and and as it's first parameter a pointer to a void. Then should that function's first parameter accept a string...
0
10315
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
11785
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
11368
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
10856
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
10047
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
8422
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
6369
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...
2
4695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3722
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.