Click here to Skip to main content
13,398,051 members (43,386 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hello all,

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

myStruct *pMyStruct = new myStruct[structSize];


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

string *pMyList;


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

string *pTempList = new string[listSize];


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

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 28-Nov-10 23:50pm

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.180216.1 | Last Updated 29 Nov 2010
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100