简体   繁体   中英

AccessViolationException when using std::basic_ifstream::get() in C++/CLI, why?

When I try to run this:

#include <tchar.h>
#include <fstream>

int _tmain(int argc, TCHAR *argv[])
{
    std::basic_ifstream<TCHAR> file("TestInput.txt");
    file.get();
}

I get an AccessViolationException with this stack trace:

ntdll.dll!_RtlpWaitOnCriticalSection@8()  + 0xae bytes  
ntdll.dll!_RtlpEnterCriticalSectionContended@4()  + 0xa1 bytes  
ntdll.dll!_RtlEnterCriticalSection@4()  - 0x1f885 bytes 
msvcr120.dll!__lock_file()  + 0x2ce45 bytes 
[Managed to Native Transition]  
MyProject.exe!std::basic_filebuf<char,std::char_traits<char> >::_Lock() Line 355    C++
msvcp120d.dll!std::basic_istream<char,std::char_traits<char> >::_Sentry_base::_Sentry_base()  + 0x55 bytes  
msvcp120d.dll!std::basic_istream<char,std::char_traits<char> >::sentry::sentry()  + 0x32 bytes  
msvcp120d.dll!std::basic_istream<char,std::char_traits<char> >::get()  + 0x5c bytes 
[Managed to Native Transition]  
MyProject.exe!wmain(int argc = 0x2, wchar_t** argv = 0x054AA3F8) [line # removed]   C++
MyProject.exe!__tmainCRTStartup()    [line # removed]   C
[Managed to Native Transition]  
mscoreei.dll!__CorExeMain@0()  + 0x71 bytes 
mscoree.dll!_ShellShim__CorExeMain@0()  + 0x227 bytes   
mscoree.dll!__CorExeMain_Exported@0()  + 0x8 bytes  
ntdll.dll!___RtlUserThreadStart@8()  + 0x27 bytes   
ntdll.dll!__RtlUserThreadStart@8()  + 0x1b bytes    

Why does this happen, and how can I avoid it when trying to read a file?

It was because I was compiling with the _DEBUG macro (left over from before converting from native). Removing it fixed the problem.

It sounds like you have macro's doing unexpected things. When you need to figure out what happened in Visual C++, have it dump the preprocessor output. Details on doing that are documented here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM