473,671 Members | 2,475 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Vector of pointers

Hi,
As a c++ newbie, i'm trying to figure out stuff mysself and i have a
problem, thougt someone could help.

Here's the code:

#include <iostream>
#include <vector>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

void test()
{
vector<Test*v;

for (int i = 0; i < 5000000; i++)
{
v.push_back(new Test());
}

for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
}

int main()
{
for (int i = 0; i < 10; i++)
test();

string a;
cin >a;

return 0;
}

Since i delete the pointers in my vector i thought there's no memory
problems with this code. But when i compile it using visual stuido
2005, it ends up using ~25mb memory at the end of that loop. So i tried
it with gcc on cygwin and it worked just fine, final mem usage: 900kb.
(peaks to 100mb both ways)

Am i missing something? Can that code leak memory when it runs without
any exceptions before cleanup code?

Thanks.

Nov 20 '06 #1
11 5024
"Antimon" <an*****@gmail. comwrote in news:1164060480 .203230.172480
@j44g2000cwa.go oglegroups.com:
Hi,
As a c++ newbie, i'm trying to figure out stuff mysself and i have a
problem, thougt someone could help.

Here's the code:

#include <iostream>
#include <vector>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

void test()
{
vector<Test*v;

for (int i = 0; i < 5000000; i++)
{
v.push_back(new Test());
}

for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
}

int main()
{
for (int i = 0; i < 10; i++)
test();

string a;
cin >a;

return 0;
}

Since i delete the pointers in my vector i thought there's no memory
problems with this code. But when i compile it using visual stuido
2005, it ends up using ~25mb memory at the end of that loop. So i tried
it with gcc on cygwin and it worked just fine, final mem usage: 900kb.
(peaks to 100mb both ways)

Am i missing something? Can that code leak memory when it runs without
any exceptions before cleanup code?
Yep. The memory that you (correctly) delete doesn't necessarily get
handed back to the operating system. The C++ runtime on whatever
platform you're on may be doing some sort of memory caching... not giving
the memory back to the OS (typically a "slow" operation, YMMV) but
holding on to it to allocate it back into the program when requested.
Nov 20 '06 #2

Antimon wrote:
Hi,
As a c++ newbie, i'm trying to figure out stuff mysself and i have a
problem, thougt someone could help.

Here's the code:

#include <iostream>
#include <vector>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

void test()
{
vector<Test*v;

for (int i = 0; i < 5000000; i++)
{
v.push_back(new Test());
}

for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
}

int main()
{
for (int i = 0; i < 10; i++)
test();

string a;
cin >a;

return 0;
}

Since i delete the pointers in my vector i thought there's no memory
problems with this code. But when i compile it using visual stuido
2005, it ends up using ~25mb memory at the end of that loop. So i tried
it with gcc on cygwin and it worked just fine, final mem usage: 900kb.
(peaks to 100mb both ways)

Am i missing something? Can that code leak memory when it runs without
any exceptions before cleanup code?
Nope, you haven't missed anything. The language does not impose a
requirement over when the allocated memory is returned to the heap by
the platform. Thats implementation defined.

I'ld suggest a try-catch block in case a std::bad_alloc is thrown.

int main()
{
try
{
// do stuff
}
catch( const std::exception& e )
{
std::cerr << "error: ";
std::cerr << e.what() << std::endl;
}
}

Nov 20 '06 #3
Thanks alot for helping, just checked it and yes when something else
needs memory, it starts to give that memory back to os.
On Nov 21, 2:02 am, "Salt_Peter " <pj_h...@yahoo. comwrote:
Antimon wrote:
Hi,
As a c++ newbie, i'm trying to figure out stuff mysself and i have a
problem, thougt someone could help.
Here's the code:
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test();
};
Test::Test()
{
}
void test()
{
vector<Test*v;
for (int i = 0; i < 5000000; i++)
{
v.push_back(new Test());
}
for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
}
int main()
{
for (int i = 0; i < 10; i++)
test();
string a;
cin >a;
return 0;
}
Since i delete the pointers in my vector i thought there's no memory
problems with this code. But when i compile it using visual stuido
2005, it ends up using ~25mb memory at the end of that loop. So i tried
it with gcc on cygwin and it worked just fine, final mem usage: 900kb.
(peaks to 100mb both ways)
Am i missing something? Can that code leak memory when it runs without
any exceptions before cleanup code?Nope, you haven't missed anything. The language does not impose a
requirement over when the allocated memory is returned to the heap by
the platform. Thats implementation defined.

I'ld suggest a try-catch block in case a std::bad_alloc is thrown.

int main()
{
try
{
// do stuff
}
catch( const std::exception& e )
{
std::cerr << "error: ";
std::cerr << e.what() << std::endl;
}

}- Hide quoted text -- Show quoted text -- Hide quoted text -- Show quoted text -
Nov 20 '06 #4
Antimon wrote:
[top posting redacted]
Hi and welcome! Glad the group was able to answer your question.

Just a recommendation for future posting, it's considered poor etiquette
to top post (i.e. reply *above* the text you're responding to) in this
group.

You should edit the text you're replying to, including stripping
signatures, and intersperse your comments with the text.

Example:

Antimon wronte:
something red floyd wants to respond to
red floyd's response.
something else red floyd wants to talk about
red floyd's response.

etc...

Hope this helps, don't want you to get flamed for netiquette issues,
when you're looking for help.
Nov 21 '06 #5

"Antimon" <an*****@gmail. comwrote in message
news:11******** **************@ j44g2000cwa.goo glegroups.com.. .
Hi,
As a c++ newbie, i'm trying to figure out stuff mysself and i have a
problem, thougt someone could help.

Here's the code:

#include <iostream>
#include <vector>

using namespace std;

class Test
{
public:
Test();
};

Test::Test()
{
}

void test()
{
vector<Test*v;

for (int i = 0; i < 5000000; i++)
{
v.push_back(new Test());
}

for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
}

int main()
{
for (int i = 0; i < 10; i++)
test();

string a;
cin >a;

return 0;
}

Since i delete the pointers in my vector i thought there's no memory
problems with this code. But when i compile it using visual stuido
2005, it ends up using ~25mb memory at the end of that loop. So i tried
it with gcc on cygwin and it worked just fine, final mem usage: 900kb.
(peaks to 100mb both ways)

Am i missing something? Can that code leak memory when it runs without
any exceptions before cleanup code?

the allocator for vector may be keeping the allocated memory.
You could write your own allocator to avoid this.

Nov 21 '06 #6

Antimon wrote in message
<11************ **********@m7g2 000cwm.googlegr oups.com>...
>Thanks a lot for helping, just checked it and yes when something else
needs memory, it starts to give that memory back to os.
What red floyd said. (dang, red, I've never seen a slap-in-the-wrist put so
nicely! ).

See below...
>Antimon wrote:
Here's the code:
#include <iostream>
#include <vector>
using namespace std;
class Test{
public:
Test();
};
Test::Test(){}
void test(){
vector<Test*v;
for (int i = 0; i < 5000000; i++){
v.push_back(new Test());
}
for (vector<Test*>: :iterator i = v.begin(); i != v.end(); i++)
delete *i;
// Try this here and see what your results are.
// [ just out of curiosity ]

static bool stopper( true );
if( stopper ){ // so it doesn't print 10 times.
cout<<" v.size()="<<v.s ize()<<std::end l;
cout<<" v.capacity()="< <v.capacity()<< std::endl;
}

vector<Test*>() .swap( v );

if( stopper ){ // so it doesn't print 10 times.
cout<<" v.size()="<<v.s ize()<<std::end l;
cout<<" v.capacity()="< <v.capacity()<< std::endl;
stopper = false;
}
}
int main(){
try{
for (int i = 0; i < 10; i++)
test();
}
catch( const std::exception& e ){
std::cerr << "error: ";
std::cerr << e.what() << std::endl;
}
string a;
cin >a;
return 0;
}
Memory change, same?

--
Bob R
POVrookie
Nov 21 '06 #7
BobR wrote:
>
What red floyd said. (dang, red, I've never seen a slap-in-the-wrist put so
nicely! ).
Thanks. I think :-)

Wasn't really trying for the slap-on-the-wrist effect; I was aiming more
for the "arm around the shoulder, friendly advice" effect.

Nov 21 '06 #8
red floyd wrote:
Hi and welcome! Glad the group was able to answer your question.
Thanks alot.
Just a recommendation for future posting, it's considered poor etiquette
to top post (i.e. reply *above* the text you're responding to) in this
group.

You should edit the text you're replying to, including stripping
signatures, and intersperse your comments with the text.
And thanks for the advice too. I'm not used to newsgroups much but
gonna learn :)

Take care..

Nov 21 '06 #9
BobR wrote:
vector<Test*>() .swap( v );
I tried this, yes it trims the vector to 0 size but it doesnt release
that memory.

Output:
v.size()=500000 0
v.capacity()=53 14959
v.size()=0
v.capacity()=0
Memory change, same?
Same, but when systems runs out of memory somehow, it starts to
deallocate memory (drop from 25mb mem usage to 600kb) caching seems
fine but 25mb is a huge amount to just cache :)

Btw, i tried this with mingw too, it is just like visual c++. Only gcc
on cygwin releases all memory allocated after test() calls.

Thanks.

Nov 21 '06 #10

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

Similar topics

9
2968
by: luigi | last post by:
Hi, I am trying to speed up the perfomance of stl vector by allocating/deallocating blocks of memory manually. one version of the code crashes when I try to free the memory. The other version seem to work. I would appreciate someone to comment on this. Version 1 (crashes on deallocating) #include <iostream>
14
3523
by: Roland Bengtsson | last post by:
I have a class Conception and I have this in a vector, it should be: vector<Conception> vek; // vector vector<Conception>::iterator vek; // iterator to vek But what if I want to have pointers to class Conception instead? How can I do that? And how should I write to declare an iterator to this vector?
13
2138
by: Joseph | last post by:
I was doing my assignment,but encountered a problem at last step!!!!!! for easy reading, i ommited lots of other things //=====================code begin================================ class Buyer{ void start(void); friend void Buyer_run(Buyer *buyer);
11
2737
by: koperenkogel | last post by:
Dear cpp-ians, I am working with a vector of structures. vector <meta_segment> meta_segm (2421500); and the structure look like: struct meta_segment { float id; float num;
9
2305
by: kathy | last post by:
I am using std::vector in my program: func() { std::vector <CMyClass *> vpMyClass; vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); vpMyClass.push_back(new CMyClass()); //???? Required ??????????????//
8
3612
by: jagguy | last post by:
I am a little confused with the basic concept of vector of pointers. The vector is easy enough. Say you want a vector of pointers to int. The integers are not created outside the vector so all we get is this and it doesn't work vector<int*> ones; ones->push_back(7); //this failed to *ones.push_back(7) ones->push_back(8);
5
5518
by: Gert Van den Eynde | last post by:
Hi all, It's probably trivial but I can't figure it out... I have a templated class template <typename T, typename uclass A I wish to fill a vector with pointers to objects of class A. I tried to declare the vector as std::vector< A<>* vA
6
3256
by: lokchan | last post by:
i want to create a vector of pointer s.t. it can handle new and delete but also have std::vector interface can i implement by partial specialization and inherence like follow ? #include <vector> #include <algorithm> template <typename T> struct delete_ptr {
6
3993
by: Jia | last post by:
Hi all, I have a class foo which has a static vector of pointers of type base class, and a static function to set this vector. #include <iostream> #include <vector> using namespace std; class super{ protected:
4
3505
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token vector_static_function.c:21: error: expected constructor, destructor, or type conversion before '.' token
0
8924
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...
1
8602
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
8672
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
7441
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
5702
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
4412
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2817
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
2058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1814
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.