Skip to content

GC.KeepAlive for UnmanagedImages #399

@GoogleCodeExporter

Description

@GoogleCodeExporter
What steps will reproduce the problem?
1. Build the attached program.
2. Run the attached program outside of the debug environment.
3. Inspect the generated test.png file.


What is the expected output? What do you see instead?

The file should be black. Running under a debug environment it will be. Running 
under an optimizing JIT it will be white, unless you uncomment the GC.KeepAlive 
line.


What version of the product are you using?

AForge.NET Framework-2.2.5.
Tested under .NET version 2.0.50727.8009 and 4.0.30319.34209.


Please provide any additional information below.

This happens because after you obtain the ImageData pointer, the GC is free to 
garbage collect the UnmanagedImage (even though it is a function parameter, 
apparently in scope).

This will free the unmanaged memory allocated for the image, and the second 
image will be allocated in its place. Setting all bytes on ImageData to white 
will thus affect the second image. The solution here is to uncomment the 
GC.KeepAlive line.

There are an awful lot of places where AForge does something similar across the 
entire framework (e.g. obtain the pointer, and go through the image using an 
unsafe block, which by the way, in no way prevents this optimization). It's 
terribly hard to get a comprehensive fix. User code (e.g. the Accord framework) 
also does this a lot.

Typically this won't cause problems, but it's there waiting to happen, whenever 
an UnmanagedImage might be freed by the GC (and not duly disposed of).

Original issue reported on code.google.com by ncruces on 5 Mar 2015 at 7:15

Attachments:

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions