how to avoid memory leaking

Adam D. Ruppe destructionator at gmail.com
Mon May 13 07:02:06 PDT 2013


actually the output array doesn't need to be there at all, I 
could compress on the fly, adding the filter byte to a much 
smaller buffer, then writing straight out to the file. Then the 
only big array would be the one in the image class itself, which 
is easy to manage.

In fact, I did another file originally called imagedraft.d that 
does pngs as lazy ranges. Doesn't look like I ever posted that 
one to github. I think it can actually read more png files too.


But in any case, switching to that will be harder since I don't 
even remember how to use it.



ANYWAY, I added a new function to png.d:

void writeImageToPngFile(in char[] filename, TrueColorImage 
image);


Use it like this:

            // and finally write the data to a png file
            
writeImageToPngFile("images/"~toHexString(md5Of(curtrans))~".png", 
i);


And see if things are any better. This one uses malloc/free for 
its temporary buffer and uses the Compress class from std.zlib to 
do it one line at a time instead of the big function, so 
hopefully its temporary buffer will be more manageable too.

It also explicitly deletes the compressed data buffer when it is 
done with it, after writing to the file. (I know delete is 
deprecated but switching this to use an malloced buffer would 
have needed me to totally duplicate the std.zlib class so meh, we 
can do it if needed but for now let's just try this).


Since my computer can't handle the large arrays anyway, I can't 
test this for sure but I expect you'll see some difference here. 
If you've changed TrueColorImage to use malloc/free as well that 
would probably help as well (none of this keeps a reference to 
data, so free it in truecolorimage's destructor and you should be 
ok.)


More information about the Digitalmars-d-learn mailing list