When dealing with naked pointer, what is the best way to make sure that memory get released? For example, implemented linked-list using C style.
#include <iostream>
using namespace std;
struct node {
int value;
node* next;
node( int value ) : value( value ), next( NULL ) {
}
};
void put( node* root, int value ) {
node *newnode = new node( value );
while( root->next )
root = root->next;
root->next = newnode;
}
node* pick( node *root ) {
if( root->next ) {
node* temp = root->next;
root->value = root->next->value;
root->next = root->next->next;
delete temp;
return root;
}
return NULL;
}
struct las {
private:
node *a;
public:
las() {
a = new node( 0 );
a->next = new node( 1 );
}
void next() {
node* na = new node( 0 );
while( a->next ) {
pick( a );
int count;
int value = a->value;
for( count = 1; a->next && a->value == a->next->value; count++ ) {
pick( a );
}
put( na, count );
put( na, value );
}
delete a;
a = na;
}
friend
ostream& operator <<( ostream& os, const las& olas ) {
node* root = olas.a;
while( root->next ) {
root = root->next;
os << root->value;
}
return os;
}
};
int main() {
las* ls = new las();
int n = 10;
for( int i = 0; i < n; i++ ) {
cout << *ls << endl;
ls->next();
}
delete ls;
return 0;
}
I’m not the author of this code, so how can I find out is there memory in this program?
An alternative to a heap checker if you know which object may be a culprit is to manually instrument your code:
Then:
This kind of light weight check can be built into a unit test (or even production code), ensuring that you pick up the leak as soon as possible. You might wrap it in NDEBUG so as to remove cleanly from a release build when wanted.