C++ Visual Studio 2008, delete() operation crashes program - c++

Since some days, I have been facing a problem in Visual Studio 2008, related to my C++ software.
If I set Visual Studio settings to "Release Win32" mode, it works fine.
But if I set it to "Debug Win32", it has crash problems when using delete. Compiling is alright, but, when running, the software crashes on 1st "delete" it meets.
Consider this snaphsot:
As you can see, when software arrives to "delete temp;" command execution, it crashes showing the message:
Debug Assertion Failed!
Program...
Expression _BLOCK_TYPE_IS_VALID(pHead->nBlockHouse)
What is the problem?
How to solve it?
Why in "Release" mode it doesn't have any errors?
Thanx

You should only delete what you new and delete[] what you new[]. Nothing else. You're also trying to use a null pointer to call a function. What happens when you try to call a method of nothing? Well, it can't be anything good.

You have temp = NULL and on the next line you call a method on it? And then you try do delete it?
In addition to that assertions aren't "errors". Assertions are there in debug mode to declare that you are asserting a certain condition (these often are also included throughout libraries such as the MFC) and if your assertion fails it calls code to inform you about it and give you the chance to break into the debugger in order to debug the issue.

The debugger does an "assertion". This is an additional check for correctness of the code like eg: "assert that the pointer is not null.". It's good that it is doing so, because it helps finding errors. I agree to anybody who claims that the message emitted by the debugger does not help finding the source for the error.

Related

What does this debug assertion failed mean?

Expression: header->_block_use == block_use || header->_block_use ==
_CRT_BLOCK && block_use == _NORMAL_BLOCK
What does this mean? It has something to do with a header?
I found in my code where after I step over it returns the debug assertion failure, just this one line of code works in other projects.
Is there a linker setting or c/c++ setting that I have to remove?
The assertion that you are hitting is part of the Microsoft Visual C/C++ runtime libraries, specifically related to the debug heap. Calling malloc/free and using the new/delete operators leads to calls to the CRT heap functions, which perform internal consistency checks using these assertions.
It's very likely that the assertion is hit as a result of a memory safety bug, for example trying to delete a garbage pointer, double-free, etc. If you are unable to find it, the ASAN tool can help by keeping closer track of memory operations and raising errors when your code does invalid things. Without these close checks, mistakes in your code can corrupt a data structure, and the crash could occur much, much later in unrelated code.
For Visual Studio, it involves a few steps: the "C++ AddressSanitizer" feature must be installed using the Visual Studio installer, and the address sanitizer must be enabled in the project properties under C/C++ -> General.
Languages such as C and C++ offer an assert(...expression...) facility that is typically used during debugging ... and omitted from the final delivered product. The ..expression... being "something that should always be False."
If the expression turns out not to be False, then it throws a runtime exception containing the exact text of expression. Which is exactly what a developer would like to see, because: "the whole idea is that this should never, ever, ever happen!"
Ordinarily, published versions of applications are compiled in such a way that all of the assert() statements are ignored: they are "no-ops."

how to debug "Invalid parameter passed to C runtime function"?

Background
I've got about a terabyte of files with raw data, with a relatively small subset of labelled data. I've written c++ code (calling some ancient MSVC++2003 code I heavily modified to get it to compile on recent compilers) to aggregate the annotated data slices.
A big part of that labelled data is concentrated in one file, but that file turns out to be the one where my program crashes.
Problem
I'm getting
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
terminate called after throwing an instance of 'int'
In my Qt output window, and windows tells me the same in a popup, but at this point it's too late to get any useful info out of the executable / debugger it seems (though I'm not experienced at all with Qt's debugger).
What I have tried
I've googled all over and found plenty of people with this error message but it's so generic that none of their issues could be the same as mine, and there's such a long list of different C runtime functions that sifting through all of them is slow and it doesn't seem to help.
My question
"Find a man a bug, and you help him for a day. Teach a man to debug and you help him for a lifetime. Post the way on stackoverflow and you help many men and get a lot of upvotes."
Is there a generic method to find what C runtime function the problem was and what the argument was? Did I miss some fancy debugger features? Is there anything else you could recommend or info I could provide?
I'd hope to get a catch-all answer to this to help everyone with this problem, not just me, but I'll be glad if I'm helped too of course.
Specific to my problem:
My stack trace is as follows:
0 ntdll!DbgBreakPoint 0x7727000d
1 ntdll!DbgUiRemoteBreakin 0x772ff156
2 ?? 0x6f06eaa1
3 KERNEL32!BaseThreadInitThunk 0x7501338a
4 ntdll!RtlInitializeExceptionChain 0x77299902
5 ntdll!RtlInitializeExceptionChain 0x772998d5
6 ??
and gdb can't get a better trace it seems (anything I try to do with it gets me a timeout error).
After trying a couple more functions just to be sure everything gave a timeout trying "backtrace" once again did give me a result. I guess I just never put this much time in gdb after it timeouting on me once.
That said, I might be able to find something with this new info. Consider my specific problem closed, but my general point is still valid I believe: I've now found the function with the problem (I think), but not why it is a problem, nor what the invalid parameter is. Even better, I've traced it to a line where it says "throw 1". So now I'm assuming windows/Qt translates that to the "invalid parameter". But it's not true.
It can just be some bad code, it does not even need to be a C function, and nothing needs to be wrong with your parameters.
...
#17 0x00c17d72 in libstdc++-6!.cxa_throw () from C:\Qt\5.5\mingw492_32\bin\libstdc++-6.dll
No symbol table info available.
...
Since the log is printed to the debug console then it should be reported by OutputDebugStringA function. You can place a breakpoint on the function to see who results in that log. To place a breakpoint on a function you can Ctrl+B in Visual Studio and enter function name:
But this might not work, or you may have too many other messages logged using OutputDebugStringA. Usually Invalid parameter passed to C runtime function is reported by _invalid_parameter, so, you may as well try to place a breakpoint on _invalid_parameter function. This might not work as well because it could be reported from some other system dll that your process links to: ntdll.dll, KernelBase.dll etc. To place a breakpoint on a function exported by a dll you need to use: <dll>!<exportname>:
_invalid_parameter
ntdll.dll!__invalid_parameter
KernelBase.dll!__invalid_parameter
msvcrt.dll!__invalid_parameter
ucrtbase.dll!__invalid_parameter
All of these are different functions and you can see their addresses:
In my case only when I set a breakpoint on ntdll.dll!__invalid_parameter I was able to see backtrace and the log message was caused by GetAdaptersAddresses winapi. The reason breakpoint on OutputDebugStringA wasn't helpful was because the log was printed through DbgPrint api. Placing breakpoint on DbgPrint works in this case.
In Visual Studio 2017 at least, you can hit CTRL+B and add a function breakpoint on _invalid_parameter. This will stop your program at the point where the message would have been logged, which will let you find the offending function in the call stack. It will work even if someone else's code undoes your call to _CrtSetReportMode().
Things I learned from this question (and that might help people searching for this question) :
Turns out that this error could be traced back to a line of code saying
throw 1;
This means It can just be some bad code, it does not even need to be a C function, and nothing needs to be wrong with your parameters. Searching your code and libraries' source for "throw"
Turns out that getting timeouts on gdb are not an indicator of anything. Keep trying things and retrying and maybe at one time you might get a stack trace.
Personally, on a Linux terminal, I use gcc for compiling and gdb for debugging. To compile a program with debugging options using gcc, you simply have to add a -g to your other flags. Ex:gcc file.c -o file -std=c99 -g. You can then type gdb file and you enter into an interactive debugger. Among other helpful things, you can run the program, call functions and insert breakpoints. For a full and well explained usage go to this website-http://www.tutorialspoint.com/gnu_debugger/index.htm
I ran into this same error message "Invalid parameter..." while debugging a windows driver.
The technique on this page, even though for Windows and not exactly addressing for this question, might be useful to someone who is looking for this particular error message. IOW HTH..
http://dennisyurichev.blogspot.com/2013/05/warning-invalid-parameter-passed-to-c.html
So in summary you have to narrow down specific to your environment where a debug string is being output by possibly a debugging "helper" library function. Once known, set a breakpoint there and then look back up the call stack. IMHO, it's a very clever solution to what can be a tough location to find.
If you are using MinGW only (no Visual Studio build stuff). Try compiling your application for the Console subsystem instead of the Windows subsystem when building debug version. In that case when an invalid argument is passed to a C function the function will fail and will trip your error handling code instead of the standard library's error box which should give you better control over what is happening.

c++ weird error message

Someone has reported a bug in my program, which brings up the following error message:
The error occours in a C++ DLL of the program, which was compiled by VS2008. I can reproduce the error, but am not able to find out what´s the problem. I´ve already done a bunch of tests for memory leaks or wrong alloctions, but with no success.
Now the weird thing: when I add a main function to the code, compile it as an EXE and then run the exactly same thing, all is ok. The error occours only as a DLL.
The next strange thing is, that when I press "Ignore", the program continues and does its job as expected.
So, I´m looking for 2 types of answers:
- Answers that help me find the bug
- Answers that help me to "auto-ignore" or hide this errormessage, so that it does not occour. That would be ok, since there is no difference in the result.
I´m thankful for any help or advise.
Thanks!
Update
Like Joachim Pileborg said, I´ve created a simple test c++ project, that calls my DLL, and it works perfectly! The program that normally calls the DLL is written in DELPHI, so I think it could be a bug of DELPHI... Weird: The call of the DLL works for 99.9999..%, but in one specific case, there occours an error IN the Dll. It´s not the call that fails... Really, really strange story :S
Ok... that is a negative number. The simpler thing... perhaps your code is doing a malloc with an invalid\negative size?
The strange thing is that that number in binary is 11111111111111111111111111111100, probably your size calculation is wrong. It can be however a more complicated error, for example due a buffer overflow.
You should not ignore this error at all, can be a symptom of a more complicated and dangerous error.
Try to debug your allocation, try to get exactly the piece of code that is doing this invalid allocation.
You can overload the new operator or redefine the malloc replacing them your debug functions where you can check the passed arguments (size).
4294967292 - that is (unsigned)-4. You are either doing some computation of the size to be allocated wrong, some integer has overflown or somesuch.
I'd try to put a breakpoint on malloc (or whatever allocation function that is) and check where does the bad value come from.
Through the debugger, I was able to see the call stack, and what function in the code displayed the error. After searching for this routine, I could find out how to disable displaying it.

C++ / VS 2010: Bug(s) occur only when running without a debugger

This is a twisted problem. When I run my program using F5 in Visual Studio, everything works fine. If I start it without the debugger, or from outside VS, a few nasty bugs which I can't locate occur.
I suspect this is caused by the debugger randomizing all uninitialized variables, wheras "outside", they are set to 0. I must be using a variable without initing it somewhere...
Are there other possible explanations?
What should I do to find the bug - I can't use a debugger for it can I
How come the debugger in VS doesn't detect the use of an unitialized variable, if that's the case
As Hans Passant says, you have it the wrong way round. In Debug, memory is initialised, but in release it could be anything.
In general, if you have something going wrong in release that doesn't happen in debug then it could be down to a few things:
Relying on uninitialised variables as you said.
Optimisations changing the semantics of your code. This will only happen if you write code that is relying on ill-defined behaviour. For example, assuming that function arguments are evaluated in a specific order, or relying on signed integer overflow, or any number of things.
It's a timing issue that shows up more often in release builds due to the better performance. These most often occur in multithreaded applications.
You use different libraries in debug and release and rely on the different behaviour between them.
You can use the debugger to attach to a running program. I think it's in the 'Debug' menu in VS and is called 'Attach to process...'. Make sure that you generate debug symbols for release builds so that you get a usable call stack.
I had a similar problem recently except it was even weirder. The code worked fine when I ran release in visual studio, but when I ran the program outside visual studio (just clicked the .exe) it would do this very big bug.
Turned out it was because of:
angle = MathHelper.ToRadians(angle);
When ever angle was 0 it would fail and produce some weird results.
I fixed it by simply changing it to:
angle = MathHelper.ToRadians(angle+.01f);
Very very annoying problem for something so small. Hopefully this helps others find similar errors.

C++ Segmentation Fault Only External to Eclipse

I have developed a C++ application in Eclipse. When run outside of Eclipse, it takes a segmentation fault after a consistent number (4) of user actions. It did not seem like anything special at first. I thought I would just use Eclipse to debug through the application and find the bug. However, when I run the application from Eclipse, it runs just fine. Does anyone have recommendations on how to troubleshoot this problem??
Thanks.
The codebase is too large to display here, but I've narrowed down the line of code which causes the segmentation fault:
SDL_Surface* textSurface = TTF_RenderText_Solid( font, text.c_str(), color );
The odd part about this is it calls this line of code hundreds of times before failing on the exact same call. The values of font and color are constants defined elsewhere and passed in each time. So they are the exact same every time. The value of text is "-".
First make sure you run the same version within eclipse as on the commandline release vs debug.
Some bugs will change because of different compiler settings or just being debugged. These are often caused by uninitialized data. Memory debugger tools like valgrind can you help find these kind of problems as they can randomize the contents of uninitialized data.
Also make sure all warnings are on in your compile settings. The compiler will then warn you about potentialy incorrect stuff.
Edit:
Yes -Wall and -pedantic is fine for getting all warnings.
Sometimes with hard to find memory errors the error is not actually where the segfault occurs. The segfault only occurs because of earlier errors that went unnoticed. Best to use a memory debugger like valgrind. Otherwise you will have to scrutinize a lot of code.
At the recommendation of Node (see comments on original question, I ran my app through Valgrind. After cleaning up memory management issues identified by Valgrind, my problem is gone. Thank you!