c++ Unhandled exception - how to debug - c++

I have a problem when running a testcase in debug-mode: I get a pop-up-box with the message "Unhandled exception at 0x7c812fd3 in Test.exe: 0xE0000003: 0xe0000003.". The code breaks in free.c:
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0)
{
errno = _get_errno_from_oserr(GetLastError());
}
}
at line "retval =..." with _crtheap = 0x00df0000 and pBlock = 0x967c93d3. The call stack breaks at "kernel32.dll!7c812fd3() " and another entry further down in the call stack:
">msvcr100d.dll!_free_base(void * pBlock=0x967c93d3) Line 50 + 0x13 bytes".
I have googled quite a bit and the problem might come from freeing memory severel times.
Despite this vague and messy description can anyone hint how to locate the problem ? and maybe how to fix it ?
What strikes me a bit odd is that I do not experience this when running the test in release-mode...
Kind regards,
Svend

Have you tried to run these testcases under visual studio debugger?
Debugger should catch this exception and you can verify call stack and locate where issue is.

Related

FILE * creation error: Unhandled exception (ucrtbased.dll) Access violation reading location

I'm working with a simple fopen, fwrite, fflush, fclose body of code. For some reason, however, every time I try to create a FILE * object, it crashes. My code is below.
//fopen
FILE * f_data = fopen("out.txt", 'wb'); // BREAKS HERE
if (f_data == NULL) { printf("fopen failed!"); }
//fwrite
int fwritten = fwrite(data, 1, content_length, f_data);
if (fwritten == 0) { printf("fwrite failed!"); }
//fflush
int flush = fflush(f_data);
if (flush != 0) { printf("fflush failed!"); }
//fclose
int close = fclose(f_data);
if (close != 0) { printf("fclose failed!"); }
Whenever I run this code, I get the following error:
Unhandled exception at 0x5F52C795 (ucrtbased.dll) in main.exe: 0xC0000005: Access violation reading location 0x00007762.
I've been researching this problem for about an hour now, to no avail. I've learned that this is Windows telling me I've encountered a segmentation fault, possibly from trying to dereference a NULL pointer.
If anybody has some insight on why my File * instantiation won't work, please share!
EDIT: I'm not sure it's relevant to this question but the data buffer being written is a simple string: "Hello, world, and all who inhabit it!" and content_length is set to sizeof(data).

How to solve "Access violating reading location error" in c++?

Goodday all,
I'm getting the following error:
First-chance exception at 0x67887AB7 (SDL2_mixer.dll) in Racing.exe: 0xC0000005: Access violation reading location 0xCCCCCCD4.
I think the problem could be with the pointer, but I'm not experienced enough in c++ to find it.
I'm hoping someone can tell me what I did wrong, and hopefully I can learn from it :)
Trying to call it from my gamebus.
Music Mus;
Mus.SpeelGeluid("crash");
Music class
bool Music::LoadMusic(){
//Load music
Mix_Music *gMusic = NULL;
gMusic = Mix_LoadMUS("MusicTest.wav");
Mix_PlayMusic(gMusic, -1);
bool success = true;
if (gMusic == NULL)
{
printf("Failed to load Music background song! SDL_mixer Error: %s\n", Mix_GetError());
success = false;
}
// Load sound effects
Mix_Chunk *gCrash = NULL;
gCrash = Mix_LoadWAV("Crash.wav");
if (gCrash == NULL)
{
printf("Failed to load scratch sound effect! SDL_mixer Error: %s\n", Mix_GetError());
success = false;
}
return success;
}
void Music::SpeelGeluid(string soundname){
cout << soundname << endl;
if (soundname == "crash")
{
try
{
Mix_PlayChannel(-1, gCrash, 0);
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
}
else
{
} }
Thank you for your time
You have two major problems:
First, you're using gMusic before checking whether it's NULL.
This may crash Mix_PlayMusic, and actually means that compilers may optimise out the later NULL check.
Second, and most likely the cause of your problem, you're declaring gCrash and gMusic as local variables in LoadMusic.
From the names, and your use of gCrash in SpeelGeluid, my educated guess is that you also have two global variables, or possibly member variables, with the same names where you intend to store the results of loading the files.
Your local variables are hiding these globals, and you're only modifying the local variables.
Remove the lines
Mix_Music *gMusic = NULL;
and
Mix_Chunk *gCrash = NULL;
to get rid of these local variables.
And do initialise the globals to NULL when you define them.
Check your pointers as soon as you've allocated them and handle them appropriately. You nearly do:
gMusic = Mix_LoadMUS("MusicTest.wav");
Mix_PlayMusic(gMusic, -1); // <- You're using the pointer here before you check it
bool success = true;
if (gMusic == NULL) // <- this needs to be immediately after assignment
That's just from the code you've pointed. It's also possible you've missed a generic initialisation call from the SDL2_mixer.dll.
Do debug it and step through line by line so you know which bit is causing the error.

luaL_dofile Error

Error at line "luaL_dofile" and debugger doesn't show anything about error.
I can use command "luaL_dostring" but I don't know why I can't dofile.
My code is following:
const char* file = "/app_home/data/minigames/mg_hint_machine_2.lua";
ret = luaL_dofile(LS, file);
if(ret != 0){
PRINTF("Error occurs when calling luaL_dofile() Hint Machine 0x%x\n",ret);
}
else PRINT("\nDOFILE SUCCESS");
and debugger shows error in this line and "ret" still not get returned value from dofile.
If you want to see about error in debugger
02C2D304 7C21016A stdux r1,r1,r0 03 (02C2D300) REG PIPE LSU
Debugger points in this line and I can't understand it.
As an elaboration on superzilla's answer (upvote that answer rather than this one),
to get the error message your code needs to look like this:
const char* file = "/app_home/data/minigames/mg_hint_machine_2.lua";
ret = luaL_dofile(LS, file);
if(ret != 0){
PRINTF("Error occurs when calling luaL_dofile() Hint Machine 0x%x\n",ret);
PRINTF("Error: %s", lua_tostring(LS,-1));
}
else PRINT("\nDOFILE SUCCESS");
Your change (in the comments) changed the luaL_dofile to a luaL_dostring, which is why you're getting unexpected error message ( as mentioned here ).
Putting this in the body of your if statement will help us narrow down the problem:
printf("%s\\n",lua_tostring(LS,-1));
It'll tell us what Lua is reporting when it crashes.

"Access violation writing location" with file.getline? (Only in release build)

getting this error in an application written in C++ (VS 2010):
Unhandled exception at 0x77648da9 in divt.exe: 0xC0000005: Access
violation writing location 0x00000014.
it points to this function in free.c:
void __cdecl _free_base (void * pBlock)
{
int retval = 0;
if (pBlock == NULL)
return;
RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));
retval = HeapFree(_crtheap, 0, pBlock);
if (retval == 0) //<-----------------------right here
{
errno = _get_errno_from_oserr(GetLastError());
}
}
Via debugging I was able to determine where its actually crashing:
void MenuState::LoadContentFromFile(char* File,std::string &Content)
{
std::string strbuf;
char buffer[1028];
std::fstream file;
file.open(File,std::ios_base::in);
if(file.fail())
{
Content = ErrorTable->GetString("W0001");
return;
}
if(file.is_open())
{
while(!file.eof())
{
file.getline(buffer,128,'\n'); // <----here
strbuf = buffer;
Content += strbuf + "\n";
}
}
file.close();
strbuf.clear();
}
It crashes on file.getline(buffer,128,'\n');
I don't understand why but it's only doing it in release build (Optimizations turned off), on debug build its working fine.
Any Ideas?
I know this is an old question, but when you encounter these sorts of issues buried deep in files such as, free.c or xmemory, you may also want to double check your project configuration. Especially when the issue pertains to only certain build configurations.
For example, in MSVC check your Project Properties > Configuration Properties > C/C++ > Code Generation > Runtime Library. Make sure it consistent for all dependencies and that it is set to a Debug/Release variant depending on the current build.
I would bet that the read prior to the read crashing the application actually failed (although I'm not quite sure why it would crash). The important thing to note is that eof() is only good for determining what caused a read failure (and typically suppressing an error message). In addition, you always want to check after the read whether it was successful. Finally, I can't see any reason why you don't read an std::string directly. In summary, try to use this loop instead:
for (std::string strbuf; std::getline(file, strbuf); ) {
Content += strbuf;
}
Asked a friend for help, we came up with this Solution:
std::string strbuf;
char buffer[256] = "\0";
FILE* f = fopen(File, "rt");
while(fgets(buffer,sizeof(buffer),f) != NULL)
{
Content += buffer;
}
fclose(f);
strbuf.clear();
Works fine, still thanks for your efforts.

Why does GetLastError() return different codes during debug vs "normal" execution?

try
{
pConnect = sess->GetFtpConnection(ftpArgs.host, ftpArgs.userName, ftpArgs.password, port, FALSE );
}
catch (CInternetException* pEx)
{
loginErrCode = GetLastError();
printf("loginErrCode: %d\n", loginErrCode);
if(loginErrCode == 12013)
{
printf("Incorrect user name!\n");
exit(0);
}
else if(loginErrCode == 12014)
{
printf("Incorrect password!\n");
exit(0);
}
else if(loginErrCode == 12007)
{
printf("Incorrect server name!\n");
exit(0);
}
else //display all other errors
{
TCHAR sz[1024];
pEx->GetErrorMessage(sz, 1024);
printf("ERROR! %s\n, sz);
pEx->Delete();
exit(0);
}
When this code runs from visual studio with an intentional incorrect user name, GetLastError() returns 12014 (expected).
However, when running the same code from the command line (with the same exact incorrect username) GetLastError() returns 2? (the GetErrorMessage() does return incorrect password)
I do not understand what the difference is.
In addition, I ran the program from the command line while attaching the process to it in visual studio, to debug. I received 12014.
Whenever the debugger is involved, I get 12014. When I run the executable "normally" with the same parameters, I get 2.
Are the WinInet error codes not being found when I run the program outside of the debugger? Do I need to compile the program differently?
Any help is appreciated. Thank You.
My memory is a little hazy in this regard, but what happens if you use the m_dwError field of the CInternetException object instead of calling GetLastError()?
My guess is that something is causing the error code to be reset between when the actual error and your call to GetLastError(). I don't know why this happens when running outside the debugger but not inside the debugger. However, MFC caches the error code that caused the exception in the thrown object, so you should be able to use the cached value regardless of what API calls have happened since the exception was thrown.
GetErrorMessage() returns the correct error string because it uses this m_dwError field, rather than calling GetLastError().