In C++, if I have some dynamically allocated memory using malloc, can I free the same by calling free() from destructor and then explicitly call the destructor via class object?
Trying to do that but getting an exception.
Is it now allowed?
So here I'm explicitly calling the destructor. Is this allowed? I mean, I'm calling it to free memory. I did read that after the scope, the destructor is called implicitly. Does this mean the free() will try to happen twice?
My code snippet:
class School
{
int a;
};
class Test
{
public:
School* school;
void Run()
{
school = (School*)malloc(sizeof(School));
}
~Test()
{
if (NULL != school)
{
free(school);
school = NULL;
}
}
};
int main()
{
Test t;
t.Run();
t.~Test();
return 0;
}
new/deleteand don't call the destructor yourself, look into smart pointers, it would save you some work. Show us your code for better assessment. - anastaciufreeto release memory acquired viamallocallowed, it is the only correct way to do it. But in C++ you should generally not be usingmallocin the first place. If you are getting an exception or a crash, then there is an error in your code, but it isn't from passing amalloced pointer tofree. Please share a minimal reproducible example. Otherwise, it is very difficult to guess where you went wrong. - François Andrieuxint main() {Test t;}Then here it falls apart with a three line program:int main() { Test t. t.Run(); Test t2 = t; }. - PaulMcKenzie