QB64.org Forum

Active Forums => QB64 Discussion => Topic started by: 40wattstudio on March 03, 2020, 09:36:41 pm

Title: _Freeimage question
Post by: 40wattstudio on March 03, 2020, 09:36:41 pm
I've been using _Loadimage quite a bit and from reading the Wiki it sounds like one should preferably use it in conjunction with _Freeimage to prevent memory errors.

_Freeimage seems pretty easy to implement, but how does one test to see that it's actually working?
Title: Re: _Freeimage question
Post by: SMcNeill on March 03, 2020, 09:38:17 pm
Easiest way is just to watch memory usage in Task Manager for your program.  Without it, you’ll have a memory leak and resources will increase endlessly until your program crashes.  (Depending on program flow, of course.  Loading an image once without freeing it won’t crash a program, but to load an image inside a loop repeatedly, definitely will.)
Title: Re: _Freeimage question
Post by: 40wattstudio on March 03, 2020, 09:42:46 pm
Ok that sounds pretty simple. Is there a way to monitor it in-program as well, like by printing to the screen a list of loaded and freed images?
Title: Re: _Freeimage question
Post by: SMcNeill on March 04, 2020, 01:05:09 am
Ok that sounds pretty simple. Is there a way to monitor it in-program as well, like by printing to the screen a list of loaded and freed images?

You might be able to monitor the image handles.  Every image has an unique handle which we use to reference it in memory (Handle = _LOADIMAGE(...stuff)).

I *believe* that the first image handle usually starts around -11 and increases by -1 for each image loaded after that.  (I’m not at my PC currently, so I can’t test to be certain.)

So load one image, it’s handle value is usually -11.  The next image handle value is -12.  Then -13....

Free an image and those handles should be recycled when you load a new one.

First image loaded has a handle of -11.   Second is -12.  Third is -13....

Now, FREE the second image from memory (-12), LOAD a new image, and it *should* recycle that freed handle and have a value of -12...



So let’s say I’m loading up to 10 images in memory.  IF I’m loading and freeing them properly, as simple check of something like this would make an easy warning:

SUB ValidateHandle (Handle AS LONG)
    IF Handle < -100 THEN
        CLS
        PRINT “IMAGE MEMORY LEAK IN PROCESS!!”
        END
    END IF
END SUB

An endless loading and unloading of images would generate more than -100 handles, trip the IF, and report itself as an error for you.

**At least, I think it should work.  As I said above, I’m not at the PC currently for 100% testing.