Menu

#11 Memory leak for some Surface constructors

open
nobody
None
5
2012-12-28
2010-11-06
No

From the forum:

myl

I believe I've discovered a pretty nasty memory leak, caused by some of the Surface constructors.

Specifically Surface(Bitmap bitmap) and from looking at sdl.net source I think the bug is also present in Surface(byte[] array) and Surface(MemoryStream stream).

The following code creates and releases surfaces forever. The memorystream created from the Bitmap in SDL source is not released, so heavy leaking occurs.

string pathToMyPreferrablyBigPNGFile = "blah.png";
while (true) {
Bitmap bitmap = new Bitmap(pathToMyPreferrablyBigPNGFile);
Surface surface = new Surface(bitmap);
bitmap.Dispose();
surface.Close();
}

While the following code (which underneath calls unmanaged SDL directly), looks leak proof:

string pathToMyPreferrablyBigPNGFile = "blah.png";
while (true)
{
Surface surface = new Surface(pathToMyPreferrablyBigPNGFile);
surface.Close();
}

--------------------------------
masshuu:
=======
i would like to note that after playing around,

this.Handle = SdlImage.IMG_Load_RW(Sdl.SDL_RWFromMem(arr, arr.Length), 1);

is the source of the memory leak, which includes the constructors
public Surface(byte[] array)
public Surface(System.Drawing.Bitmap bitmap)
public Surface(MemoryStream stream)
-------------------------------------------------

myl

The code below is a hackalicious way of moving a bitmap to surface in memory, avoiding the leak.

private static Surface BitmapToSurface(Bitmap bitmap)
{
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] arr = stream.ToArray();
stream.Close();
IntPtr dest = System.Runtime.InteropServices.Marshal.AllocHGlobal(arr.Length);
System.Runtime.InteropServices.Marshal.Copy(arr, 0, dest, arr.Length);
IntPtr rwop = Sdl.SDL_RWFromMem(dest, arr.Length);
Surface surface = new Surface(SdlImage.IMG_LoadPNG_RW(rwop));
Sdl.SDL_FreeRW(rwop); //This call is not freeing the rwop, which is why we do the FreeHGlobal
System.Runtime.InteropServices.Marshal.FreeHGlobal(dest);
return surface;
}

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.