Bad image format “Invalid access to memory location”

Wow, two bad image format posts in one day. So, the previous post talked about debugging 64bit vs 32 bit assemblies. But after that was solved I ran into another issue. This time with the message:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'Interop.dll' or one of its dependencies. Invalid access to memory location. (Exception from HRESULT: 0x800703E6)
   at Program.Program.Run(Args args, Boolean fastStart)
   at Program.Program.Main(String[] args) in C:\Projects\Program.cs:line 36

Gah, what gives?

It seems that I had an interop DLL that was linking against pthreads. In debug mode, the dll worked fine on a 32 bit machine, but in release mode I’d get the error. The only difference I found was that in debug the dll was being explicity linked against pthreads lib file. Since pthread was also being built as a dynamic library, it’s lib file contains information about functions and their address, but no actual code (that’s in the dll).

After working for a while with my buddy Faisal, we decided that even though the interop dll was being built and linked properly, when it wasn’t being explicity linked to the lib file the function addresses were somehow wrong. What the compiler was actually linking against we never figured out. But, it does all make sense. If the function addresses were wrong, then when it would try and access anything in the dll it could access memory outside of its space and get an exception.

Once we explicitly linked the library as part of the linker settings of the interop dll everything worked fine.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>