Proper way to stop memory leak

New to FreeBASIC? Post your questions here.
wallyg
Posts: 124
Joined: May 08, 2009 7:08
Location: Tucson Arizona

Proper way to stop memory leak

Postby wallyg » Jul 05, 2009 22:08

I have a type definition

Type Person
dim as string PersonName
...
Declare Destructor
End Type

The question is: What is the proper way to not lose track of the memory used for the storage of the String variable in the Destructor.

I assume the default Destructor reclaims the memory used by the string variable, but since I have my own Destructor, the default Destructor does not get executed right?
vdecampo
Posts: 2982
Joined: Aug 07, 2007 23:20
Location: Maryland, USA
Contact:

Postby vdecampo » Jul 05, 2009 22:47

Variables declared with Dim will automatically destroy themselves when they fall out of scope (this includes program termination). The destructor is used to clean up any memory you may have allocated manually (ie: using Allocate, ImageCreate, New, etc...).

-Vince
counting_pine
Site Admin
Posts: 6225
Joined: Jul 05, 2005 17:32
Location: Manchester, Lancs

Postby counting_pine » Jul 06, 2009 6:32

If you have a non-default constructor, it will be necessary for it to destroy manually all the objects it contains. Strings should be set to "" to deallocate their memory, and objects should be Deleted.
cha0s
Site Admin
Posts: 5317
Joined: May 27, 2005 6:42
Location: Illinois
Contact:

Postby cha0s » Jul 06, 2009 8:00

I'm pretty sure FB handles the string deallocation for you, even if you have a non-default destructor, just like it handles string allocation in a non-standard constructor... You don't have to do memset(@this.my_string, 0, 12), for example.

Sorry, I have to work on my (64-bit) environment to get FB to a point where I can compile stuff again. ;)
counting_pine
Site Admin
Posts: 6225
Joined: Jul 05, 2005 17:32
Location: Manchester, Lancs

Postby counting_pine » Jul 06, 2009 8:59

Actually, yeah, I think cha0s is right. It probably destroys all the UDT's elements automatically, and just uses the destructor to do cleanup work beforehand, such as destroying objects you created manually earlier.

So, it probably works like this:

Code: Select all

default constructor
  manual constructor
    ...
  manual destructor
default destructor

This would make more sense actually: if there weren't default constructors/destructors, you'd have to placement-new and "placement-destroy" all the object elements yourself, which is probably a serious violation of RIAA principles.

EDIT: oops, RAII, not RIAA.
McLovin
Posts: 82
Joined: Oct 21, 2008 1:15
Contact:

Postby McLovin » Jul 06, 2009 12:10

.... nice to Cha0s around here again. :-)

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 4 guests