Click here to Skip to main content
15,886,833 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,

Let's assume that I have an array of structures, where the size is determined dynamically:

MIDL
myStruct *pMyStruct = new myStruct[structSize];


and let's assume that myStruct has a member which is a pointer to an array of strings:

MIDL
string *pMyList;


Somewhere in the code I allocate a temporary array of strings:

C#
string *pTempList = new string[listSize];


and later in the code I assign that temporary array to the instances of myStruct

MIDL
pMyStruct[i].pMyList = pTempList;


The question is how I should free the memory once I am done with the instances of myStruct.
Do I have to make a loop over [structSize] where I free pMylist for every instance of myStruct, then free pMyStruct (and then free pTempList)?

Best regards,
Enrique
Posted

1 solution

Hi Enrique,

You don't have the same interrogation about your std::strings because you know that they have their own internal memory management.

Similarly the Standard C++ Library provides std::vector<> with internal memory management.

If you used it instead of C arrays your question would look like:
.. let's assume that myStruct has a member which is a pointer to an array of strings a vector of strings:
struct myStruct
{
	std::vector<std::string> MyList;
};
Let's assume that I have an array a vector of structures, where the size is determined dynamically:
std::vector<myStruct> MyStruct(structSize);
Somewhere in the code I allocate a temporary array vector of strings:
std::vector<std::string> TempList(listSize);
and later in the code I assign that temporary array vector to the instances of myStruct
MyStruct[i].MyList = TempList;

The question is how I should free the memory once I am done with the instances of myStruct.

The answer would be: You have nothing to do, all memory is deallocated in the objects destructors which are called when they get out of scope.

cheers,
AR
 
Share this answer
 
Comments
Member 3605757 29-Nov-10 7:47am    
Hi Alain,

I see, I'm better off using the vector container.

Thanks!

Enrique
Member 3605757 30-Nov-10 8:16am    
Thank you for the clarification Ross. Yes, it would be more appropriate to use OOP and let the deconstructor free the allocated memory by the objects.

Regards,
Enrique

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900