473,586 Members | 2,702 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically allocated array question

Ok, everyone loves to talk about dynamic arrays and ptr's etc, they provide
endless conversation :) so here goes:

Will this leak memory (my intuition says yes):

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}

// It can be assumed that later on in the program vec will have
// delete called on each individual element

This example is to simulate a technique I am using involving more
complicated stuff so yes I realize there are better ways to do the above in
this simple case.

But also I will explain what I am trying to do in the bigger picture in case
anyone wishes to make suggestions.

I want to fill a container (a vector but it shouldnt matter what) with ptr's
to instances of objects. But there will be millions of these objects and I
wish to allocate them all at once and add them to the container. The
calling code doesn't really know the exact type of the object that will go
into the container, it only knows they will at least derive off the type of
the ptr in the container. BUT in reality they will all be the same object,
which is why i want to allocate them all at once... for speed and to avoid
fragmenting memory.

So the obvious solution of something like:

vector<basePtr* > vec;
vec.reserve(100 0000);
for(int i = 0; i < 1000000; ++i)
{
basePtr* pOb = CreateObject(); // virtual func
vec.push_back(p Ob);
}

isn't the solution I want

Jeff
Jul 19 '05 #1
6 3961
On Mon, 18 Aug 2003 16:30:34 GMT, "Jeff Williams" <no************ *************** ******@mfchelp. com> wrote:
Ok, everyone loves to talk about dynamic arrays and ptr's etc, they provide
endless conversation :) so here goes:

Will this leak memory (my intuition says yes):

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}
You don't need intutition for that: there is an allocation, no
corresponding deallocation, and the pointer value is lost on exit
from the function so there can not be later deallocation either.
// It can be assumed that later on in the program vec will have
// delete called on each individual element
In that case each element must be allocated via 'new'.
I want to fill a container (a vector but it shouldnt matter what) with ptr's
to instances of objects. But there will be millions of these objects and I
wish to allocate them all at once and add them to the container.


std::vector<Sma llObject> smallObjectCach e( cacheSize );

Also/alternatively check up on the fly-weight pattern, if you haven't.

Jul 19 '05 #2
Jeff Williams wrote:
Ok, everyone loves to talk about dynamic arrays and ptr's etc, they
provide endless conversation :) so here goes:

Will this leak memory (my intuition says yes):

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}

// It can be assumed that later on in the program vec will have
// delete called on each individual element
Actually it cannot be assumed. And even if vec *did* call delete,
"delete"ing every element of a dynamically allocated array is definitely an
error. You must invoke delete[] on pInts, no two ways about it.
This example is to simulate a technique I am using involving more
complicated stuff so yes I realize there are better ways to do the above
in this simple case.

But also I will explain what I am trying to do in the bigger picture in
case anyone wishes to make suggestions.

I want to fill a container (a vector but it shouldnt matter what) with
ptr's
to instances of objects. But there will be millions of these objects and
I
wish to allocate them all at once and add them to the container. The
calling code doesn't really know the exact type of the object that will go
into the container, it only knows they will at least derive off the type
of
the ptr in the container. BUT in reality they will all be the same
object, which is why i want to allocate them all at once... for speed and
to avoid fragmenting memory.


Sorry, I don't understand what you 're trying to do :-(

Jul 19 '05 #3
Dimitris Kamenopoulos wrote:

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}

// It can be assumed that later on in the program vec will have
// delete called on each individual element


Actually it cannot be assumed. And even if vec *did* call delete,
"delete"ing every element of a dynamically allocated array is definitely
an error. You must invoke delete[] on pInts, no two ways about it.


Furthermore, what you would get in the vector if your example compiled (IOW
if vec was vector<int>) is a copy of every int stored in pInts, the
"contents" of pInts[*] themselves live happily ever after and, of course,
are leaked.
[*] more accurately, the contents of the memory pointed to by pInts.
Jul 19 '05 #4
Jeff Williams wrote:
...
Will this leak memory (my intuition says yes):

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}
The code makes no sense. Your vector stores values of type 'int*' and
you are pushing values of type 'int' into it. Please, always try posting
real (or at least compilable) code.

You probably meant something like

vec.push_back(& pInts[i]);

or

vec.push_back(p Ints + i);
// It can be assumed that later on in the program vec will have
// delete called on each individual element


You can't call 'delete' on each individual element in this case. What
you can do is to call 'delete[]' on all elements at once:

delete[] vec.front();

--
Best regards,
Andrey Tarasevich
Brainbench C and C++ Programming MVP

Jul 19 '05 #5
Yes my example code was in error, let me post the correct version and clean
up my question a little:

new example code:

struct base_class { };
struct derive_class : base_class { };

void foo(std::vector <base_class*> & vec)
{
base_class* pBases = new derive_class[100];
for(int i = 0; i < 100; ++i)
vec.push_back(& pBases[i]);
}

void bar(std::vector <base_class*> & vec)
{
for(int i = 0; i < vec.size(); ++i)
delete vec[i];
vec.clear();
}

// I dont give a crap that the main func has bad prototype so dont even
bother
int main()
{
std::vector<bas e_class*> vec;
foo(vec);
bar(vec);
return 0;
}
Now, with this example only, is memory leaked? My intuition says yes
because I allocated with new[] but didnt de-allocate with delete[], so
somewhere the compiler must have stored the size of the array but it never
cleaned that up.

And just forget about the latter part of my original question, I didn't
provide enough context to make it clear and doing so would require more time
and space than most would care to read I believe.

Jeff
"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:3f415089@s hknews01...
Jeff Williams wrote:
Ok, everyone loves to talk about dynamic arrays and ptr's etc, they provide endless conversation :) so here goes:

Will this leak memory (my intuition says yes):


As far as I can tell, it will not. But only because it won't compile.

void foo(vector<int* >& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(p Ints[i]);
}


vec holds int pointers. pInts[i] is an int. Implicit conversion from int
to int * is not allowed.

// It can be assumed that later on in the program vec will have
// delete called on each individual element


That would create an error, since each individual element is *not* a
pointer to something that was allocated with 'new'. You don't get to
make up the rules for how 'new' and 'delete' are used. They are:
Anything that is created with 'new' must eventually be destroyed by
applying 'delete' to it exactly once. Anything that is created with
'new[]' must eventually be destroyed by applying 'delete[]' to it
exactly once.

This example is to simulate a technique I am using involving more
complicated stuff so yes I realize there are better ways to do the above in this simple case.

But also I will explain what I am trying to do in the bigger picture in case anyone wishes to make suggestions.

I want to fill a container (a vector but it shouldnt matter what) with ptr's to instances of objects. But there will be millions of these objects and I wish to allocate them all at once and add them to the container. The
calling code doesn't really know the exact type of the object that will go into the container, it only knows they will at least derive off the type of the ptr in the container. BUT in reality they will all be the same object, which is why i want to allocate them all at once... for speed and to avoid fragmenting memory.


That's fine, but possibly misguided. Are you sure allocating all at once
will speed it up enough to be worth the effort? Also, what if you can't
get a single, huge chunk of memory large enough to hold all of the
objects, but you *can* get 2 or 3 smaller chunks that together are large
enough?

So the obvious solution of something like:

vector<basePtr* > vec;
vec.reserve(100 0000);
for(int i = 0; i < 1000000; ++i)
{
basePtr* pOb = CreateObject(); // virtual func
vec.push_back(p Ob);


What's wrong with

vec.push_back(C reateObject());

?
}

isn't the solution I want


Why not? It looks fine to me (except for the part about CreateObject
being virtual). CreateObject could simply return the next available
object in your massive allocation.

In fact, you could make it a bit better by doing something like this:

class Cache
{
public:
Cache() : p(new SomeObject[1000000]) {}
SomeBase *CreateObject() ;
void ReleaseObject(S omeBase *);
~Cache() { delete [] p; }

private:
SomeBase *p;
};

It needs work, but at least with this you can be sure that your objects
are deleted when the Cache object is destroyed. You can even change the
implementation of Cache to allow for other methods of organizing the
SomeObjects if you find that one huge chunk of memory doesn't work so
well. Better still, you can change it to create the objects one at a
time in the usual way so that you have something nice and simple to use
during testing and debugging, and then possibly stick with if you find
that performance is good enough.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #6
On Tue, 19 Aug 2003 12:18:10 GMT, "Jeff Williams" <no************ *************** ******@mfchelp. com> wrote:
Yes my example code was in error, let me post the correct version and clean
up my question a little:

new example code:

struct base_class { };
struct derive_class : base_class { };

void foo(std::vector <base_class*> & vec)
{
base_class* pBases = new derive_class[100];
for(int i = 0; i < 100; ++i)
vec.push_back(& pBases[i]);
}

void bar(std::vector <base_class*> & vec)
{
for(int i = 0; i < vec.size(); ++i)
delete vec[i];
vec.clear();
}

// I dont give a crap that the main func has bad prototype so dont even
bother
int main()


The prototype is OK.

Your attitude is not.

That includes both the language and neglecting to study earlier answers.

Jul 19 '05 #7

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

Similar topics

2
1364
by: songfire | last post by:
Hi everybody! Just wondering if it is possible to point to variables in the heap. For example, is this okay? int * ptr_to_DAIA; // pointer to dynamically allocated integer array ptr_to_DAIA = new int ; for(i=0; i<SIZE; i++) ptr_to_DAIA=i; // now say I want a pointer that points to the element that contains value TARGET
7
3111
by: Fabian Wauthier | last post by:
Hi list, I am trying to dynamically grow a 2 dimensional array (Atom ***Screen) of pointers to a struct Atom (i.e. the head of a linked list). I am not sure if this is the right way to do it: /* Allocate 1st dimension */ if((Screen = (Atom ***) malloc(sizeof(Atom **) * Width)) == NULL) perrexit("malloc");
5
5588
by: nmtoan | last post by:
Hi, I could not find any answer to this simple question of mine. Suppose I have to write a program, the main parts of it are as follows: #include <blahblah.h> struct {
48
2228
by: Michel Rouzic | last post by:
I know it must sound like a newbie question, but I never really had to bother with that before, and I didn't even find an answer in the c.l.c FAQ I'd like to know what's the really proper way for input a string in an array of char that's dynamically allocated. I mean, I wish not to see any such things as char mystring; I don't want to see...
37
2749
by: yogpjosh | last post by:
Hello All, I was asked a question in an interview.. Its related to dynamically allocated and deallocated memory. eg. //start char * p = new char; ...
94
4681
by: smnoff | last post by:
I have searched the internet for malloc and dynamic malloc; however, I still don't know or readily see what is general way to allocate memory to char * variable that I want to assign the substring that I found inside of a string. Any ideas?
6
2620
by: bwaichu | last post by:
Is my understanding of the allocation of these correct? I used fixed sized allocations for the example below, so I realize there is some optimization that can be done to those. I would like to use these in a linked list for something else I am working on, but I want to make sure my understanding of the concept is correct. For example,...
4
6337
by: wyrmmage | last post by:
hello :) I need to make a dynamically allocated array of pointers, using a .hpp and .cpp file; how do I accomplish this? I think I know how to make an array of pointers, and I know how to make a dynamically allocated array, but I am lost as to how to put the two together... Any help would be appreciated :) -wyrmmage
7
8717
by: Serpent | last post by:
The C-FAQ describes some techniques here: http://c-faq.com/aryptr/dynmuldimary.html I was using something slightly different from the C-FAQ and I was wondering if it was legal. Say I want a two-dimensional array, like this: int x; but I want it dynamically-allocated, and I want expressions that refer
0
7911
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...
0
8200
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. ...
0
8338
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...
1
7954
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...
0
6610
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...
1
5710
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...
0
3836
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...
1
2345
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
1
1448
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.