Re: Memory deallocation does not work.
Grizlyk wrote:
christophe.chazeau@gmail.com wrote:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>
#include <iterator>
using namespace std;
class Test{
public :
unsigned char *data ;
Test(){
}
void Go(int taille)
{
data = (unsigned char*) malloc(taille);
printf("malloc : %p\n",data);
}
~Test()
{
printf("delete %p\n",data);
free(data);
}
};
vector<Test *> v;
It is dangerous - possible memory leak because vector<Test *> does not own
the object pointer point to. Use any RAII memory wrapper (see RAII here:
http://www.hackcraft.net/raii ) instead of Test *
vector<auto_ptr<Test> > v;
That is _bad_ and much more dangerous than vector<Test*>: auto_ptr<> does
not satisfy the requirements for use in a container. Formally, you have
undefined behavior. In practice, you may run into trouble as soon as vector
reallocates.
or give each address (stored in vector<Test *>) to other object, which
will keep object.
{
auto_ptr<Test> owner(new Test);
vector<Test *> v;
v.push_back(*owner);
*owner is a Test& not a Test*. Do you mean
v.push_back( owner.operator->() );
}
What happens at this "}"? The auto_ptr<Test> owner destroys the pointee. The
pointer stored in v now is invalid. Any further use is undefined behavior.
What exactly are you trying to to? Should you be headed for automatic memory
management, consider vector< shared_ptr<Test> > or a special container for
pointers that implements some ownership model.
int i = 0 ;
int main()
{
sleep(10);
for(i = 0;i<10000;i++)
{
Test *t = new Test();
t->Go(75000);
v.push_back(t);
}
sleep(10);
vector<Test *>::iterator it;
for(it=v.begin() ; it!=v.end();it++)
Do you need "it" outside of "for"?
That is a good point.
Try to inplement postfix operator ++, and you will see, that pferix ++ is
better.
"better" in which way?
Should you think of performance, your advice amounts to premature
optimization: chances are that it++ is inlined and optimized to the same
code that ++it would generate.
Avoid repeating function call "v.end()" if you are sure, that the function
will always return the same.
Very likely, this is also premature optimization.
[snip]
Best
Kai-Uwe Bux