I'm trying to thoroughly learn and understand the proper designs and techniques of freeing memories.
I wrote a very simple test class and a main function:
#include <iostream>
using namespace std;
class TestClass{
public:
bool *state;
void setState (bool b) {*state = b;}
TestClass(){state = new bool(false);
cout << "new object created in heap;state is pointing to it." << endl;}
~TestClass(){delete state;
state = NULL;
cout << "object deleted. " << endl;
cout << "pointer variable set to NULL."<< endl;
cout << "memory should be freed." << endl;}
};
int main(void){
TestClass obj; //default constructor called automatically
cout << "before:" << * (obj.state) << endl;
obj.setState(true);
cout << "after:" << * (obj.state) << endl;
return 0;
//destructor called automatically to destroy obj
}
As you see, I wrote a testClass with a Boolean pointer variable, a default constructor, a void function that changes state, and a destructor.
The output seems to work very well.
However, when I run this on valgrind to check memory leak, it says possibly lost: 72 bytes in 3 blocks. Though my definitely lost bytes and indirectly lost bytes were both 0(good).
I'd like to know what more I need to do to fix the possibly lost, or how to change my program overall to make it better in the first place.
Current update: I'm checking out how to wrap a function, smart pointer, and rule of five/zero.
Current Update 2: it's definitely the valgrind installed on my mac that has all these problems...Should immediately uninstall.
here's my actually reliable valgrind check:
==17388==
==17388== HEAP SUMMARY:
==17388== in use at exit: 0 bytes in 0 blocks
==17388== total heap usage: 2 allocs, 2 frees, 72,705 bytes allocated
==17388==
==17388== All heap blocks were freed -- no leaks are possible
==17388==
==17388== For counts of detected and suppressed errors, rerun with: -v
==17388== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)