Visual Studio 2010 kills (there is no other word) data in one of the arguments of the function in the unsafe block. What could cause this error? The following message shows
Also In VS 2015 Community Edition
go to Debug->Options or Tools->Options
and check Debugging->General->Suppress JIT optimization on module load (Managed only)
Regarding the problem with "Optimize code" property being UNCHECKED yet the code still compiling as optimized: What finally helped me after trying everything was checking the "Enable unmanaged code debugging" checkbox on the same settings page (Project properties - Debug). It doesn't directly relate to the code optimization, but with this enabled, VS no longer optimizes my library and I can debug.
Had the same issue before with a WPF application and all the solutions here did NOT solve the issue. The problem was that the Module was already optimized so the following solutions DO NOT WORKS (or are not enough to solve the issue):
The module is still loaded Optimized. See following screenshot:
To SOLVE this issue you have to delete the optimized module. To find the optimized module path you can use a tool like Process Hacker.
Double click your program in the "Process panel" then in the new window open the tab ".NET Assemblies". Then in the column "Native image path" you find all Optimized modules paths. Locate the one you want to de-optimize and delete the folder (see screenshot below): (I blurred my company name for obvious reasons)
Restart your application (with check box in step 1 correctly checked) and it should works.
Note: The file may be locked as it was opened by another process, try closing Visual Studio. If the file is still locked you can use a program like Lock Hunter
Go to Project Properties and under Build Make sure that the "Optimize Code" checkbox is unchecked.
Also, set the "Debug Info" dropdown to "Full" in the Advanced Options (Under Build tab).
When I was faced with the same problem I just had to clean my solution before rebuilding. That took care of it for me.
In Visual Studio 2017 or 2015:
Go to the Solution right click on solution then select Properties-> select all the Configuration-> Debug then click OK. After that Rebuild and Run,this solution worked for me.