all. Suppose we have pointer to a struct, which has a member that is a dynamic array (among other members).
I can free all the objects but want your opinion on the best practice for this specific situation. See the code below, that compiles and runs without segmentation fault:
#include <iostream>
struct TestStruct
{
int a; // And other members here
int *b = new int[10];
~TestStruct()
{
}
};
int main(void)
{
struct TestStruct *a_struct = new TestStruct();
// Do something with the struct
delete[] a_struct->b;
delete a_struct;
return 0;
}
This way I am assuming the memory is returned properly. However, if I move any of these deletes to the destructor, there will be segfault. That is, if I move the array deletion to the destructor (delete[] a_struct->b;
), it is no longer accessible because I deleted the pointer to the struct before (delete a_struct;
), and vice-versa, and memory leak happens.
After reading this thread C++ free all memory used by struct, it is a bit inconclusive because most of the suggestions are taken for granted to work, but there is segfault in many of them.
I have simplified the problem since the array I will use is 3D. If it is not possible to free 100% of the memory in the destructor, then I am ready to use a method just to run the loops to free the array memory and the pointer to the struct. So I want to know your take on this specific situation.