how to debug "Invalid parameter passed to C runtime function"? - c++

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.

Related

get stacktrace during an application crash - c/c++

I am a java developer trying my hands on C-C++ code.
Basically I have some build script that uses Visual Studio components to build the application libraries - dlls. We do not use Visual Studio IDE to debug.
But whenever we face some crash in our application, we have to enter the debug statements line by line and need to check the exact line of code in which it is crashing.
Is there any API in C/C++ which would write the stack trace into a file during the crash of our program?
Some kind of event listener that would be called during a program exit and that could print the stack trace and error information into a log file.
I have seen many questions related to this but I am not able to get how to handle this in code rather than debugging tools. I feel Java is very much advanced with respect to error handling.
Thanks in advance!
The Standard does not give you any facilites for this. That said, you can use OS-specific APIs to get what you want. On windows, the easiest is probably to use StackWalker. You do need to take care of SEH oddities yourself. I suggest this article for more information.
On POSIX platforms, you can use the backtrace function from glibc.
In general, both require your program to be compiled with debug information. It is also possible to create crash dumps without symbol names (see Minidumps on Windows), but you will need to decode them (which Visual Studio does for you for example, but you mentioned in your post that you don't use it).
Also, keep in mind that writing crash dumps from a crashing process is very error-prone (since you really have no idea what state your application is at that time). You might get more reliable results if you write the crash dumps from another process. Earlier I've put together a simple example out-of-process crash handler that demonstrates how to implement that.
You can use std::set_terminate to define a function to be called when an exception leaves main() additionally you can install a signal handler for SIGSEGV to catch segmentation faults.
You can get a stack trace (on Linux) using libunwind ( http://www.nongnu.org/libunwind/ ) or use the backtrace() function from libc.
One thing I sometimes do in my own exception classes is to grab and store a stacktrace in the constructor that I can then obtain where I catch the exception and print the trace of where it was thrown from.
You could use <errno.h> in C to handle your error and log them into a log file. The standard flux for the errors is stderr.
One solution to get the error is to use the function perror included in <errno.h> that will display the exact error.
To use it, put it in an error catcher.
if (!fileIsOpen())
perror("File not opened");
I hope it helped.

CPPUTest debugging - C++

I am learning TDD and using CppUTest in eclipse.
Is there any way to debug my code getting a nagging segmentation fault.
Thanks
I don't know anything special in CppUTest or Eclipse to help you, but some generic segfault debugging ideas seem appropriate here:
Add flushing print statements (e.g. printf(...) + fflush(stdout) or fprintf(stderr, ...)) to your code and see what gets printed. Do this in a binary search fashion with just a few prints at a time until you narrow down exactly where it is crashing. This sounds old fashioned but is extremely effective. Here is a guide I found googling that talks about this well-known technique: http://www.floccinaucinihilipilification.net/blog/2011/3/24/debugging-via-binary-search.html
Compile your code with debugging symbols and run it in a debugger. When you hit your segfault, ask for a backtrace and see if you can figure out what happened. When doing this it can be especially helpful to use a graphical debugger.
Run your code with a debugging tool like a debug malloc library or something from the valgrind suite. This may catch problems that are root causes of your segfaults but aren't occuring at the exact place where the segfault is generated (e.g. double frees, out of bound array access clobbering pointers used later, etc).
It would be helpful if you could add some code to your question, to give us a better idea of what you are up against. Not knowing any of the details, I would suggest the following:
Add -vto your executable's arguments in the Debug dialog. This will print the names of your test cases as they are executed. The last name that prints is likely the test where the segmentation fault occurs.
Put a breakpoint in that test case, where you call your code under test
Step into your code until the segfault occurs.
Trace back the value that caused the segfault (most often, a dangling pointer) and find out, why it was NULL or uninitialized.

Debugging C++ code in Visual Studio: Breaking out at a non-pre-determined time

I had a question about debugging in Visual Studio (2010 if it actually matters). Sometimes I am running an application and I want to break out of it to debug or to see where it has hung, etc. However, I find that very very often the "break-out point" seems to be in some random .c file in the standard library. I understand why this is (its executing some method somewhere), but I want to know where the last point it was in the code I have written is. Is there a way to do this?
If I try and "step", the debugger seems to always return something like "there is no code to debug for the current location" or something, which I am guess means that it is making its way through some machine code. Again, that's fine, but I want to know what the last executed call in my main.cpp file was; is there a way to get this information? The call stack doesn't seem to help either, it always has a list of non-sensicle calls and even if I can locate the latest point in the call stack that is from my main.cpp, it doesn't seem to provide any useful information (like a line number or a function name... I
think it's showing the mangled name).
What do most people do in this situation? I apologize, I know I'm a beginner, and I'm sorry I don't have a concrete example, but I feel I see this often at work.
Any help appreciated, thanks!
K
Once you've paused the program observe the call stack (Debug->Windows->Call Stack) at that point, find where the last layer of your code is and get there by clicking on the corresponding line in the call stack window.
The "Step Out" command, Shift+F11, will finish execution of the current function and break immediately after the return.
You can use Step Out a few times to step out of the system calls back to your code.
The "Step Into Just My Code" option sounds like it may do what you want, but I've never used it.

Finding division by zero in a big project

Recently, our big project began crashing on unhandled division by zero. No recent code seems to contain any likely elements so it may be new data sets affecting old code. The problem is the code base is pretty big, and running on an embedded device with no comfortable debug access (debug is done by a lot of printf()s over serial console, there is no gdb for the device and even if there was, the binary compiled with debug symbols wouldn't fit).
The most viable way would likely be to find all the division operations (they are relatively infrequent), and analyze code surrounding each of them to see if any of the divisor variables was left unguarded.
The question is then either how to find all division operations in a big (~200 files, some big) C++ project, or, if you have a better idea how to locate the error, please give them.
extra info: project runs on embedded ARM9, a small custom Linux distro, crosscompiled with Cygwin/Windows crosstools, IDE is Eclipse but there's also Cygwin with all the respective goodies. Thing is the project is very hardware-specific, and the crashes occur only when running at full capacity, all the essential interconnected modules active. Restricted "fault mode" where only bare bones are active doesn't create them.
I think the most direct step, would be to try to catch the unhandled exception and generate a dump or printf stack information or similar.
Take a look at this question or just search in google for info relating to exception catching in your particular environment.
By the way, I think that the division could happen as a result of a call to an external library, so it's not 100% sure that you'll find the culprit just by greping your code.
If I remember right, the ARM9 doesn't have hardware divide so it's going to be implemented in a function call the compiler makes whenever it has to perform a division.
See if your toolset implements the divide by zero handling in the same way as ARM's toolset does (it's likely that it does something at least similar). If so, you can install a handler that gets called when the problem occurs and you can printf() registers and stack so that you can determine where the problem is occurring. A possible similar alternative is that your small Linux distro is throwing a signal you can catch.
I'm not sure how you're getting your information that a divide by zero is occurring, but if it's because the runtime is spitting out a message to that effect, you always have the option of finding out where that is handled in the runtime, and replacing it with your own more informative message. However, I'd guess that there's a more 'architected' way to get your code to run (a signal handler or ARM's technique).
Finding all of the divisions shouldn't be hard with a custom grep search. You can easily distinguish that usage from other usages of the / and % character in C++.
Also, if you know what you are dividing, you could globally overload the / and % operator to have a __FILE__ and __LINE__ informing assertion. If using a makefile, it shouldn't be hard to include the custom operator code in all the linked files without touching the code.
You should use this as an excuse to invest in improving the debug-ability of your device - for both this problem and future issues. Even if you can't get live debugging, you should be able to find a way to generate and save off core dumps for post-mortem debugging (pinpointing the source or any unhandled exception immediately).
PC-Lint might help, it's like Findbugs for C++. It is a commercial product but there is a 30 money back guarantee.
Handle the exception.
Usually the exception will be handed a structure that contains the address that caused the exception and other information. You will probably have to become familiar with the microcontroller's datasheet or RTOS manual.
Use the -save-temps for gcc and find the relevant assembly for division in the generated .s file. If you're lucky it will be something fairly distinctive, possibly even a function call. If it's a function call you can use weak linking to override it with your own checked version. Otherwise locating the divisions in the assembly should give you a very good idea where they are in the C/C++ code and you can instrument them directly.
usually you could modify/override the divide-by-zero exception handler if you have access to the exception handler routines.
in case of ARM, the division is done by a library routine. and there are mechanisms to inform the user-code, when a divide by zero occurs.
see http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka4061.html
i would suggest to provide a __rt_raise() as said in the page above.
__rt_raise(2,2) will get called when the divide routine detects a divide by zero.
so you can print the LR register.
and then use addr2line to crossref it against the source line
The only way to find those conditions is the usual:
try to reproduce the problem without looking at the source (as the bug already happened you should have info on the part of the program that is affected)
if found, check the source for this point and fix it, otherwise:
2.1. grep for each / not followed by a * or / (grep "/[^/*]" i think)
2.2. find the conditions for which the code is executed and reproduce it
The exception already has the address location of the offending divide by zero code. The CPU saves register contents when a exception occurs including the PC(program counter). Your OS should pass this information along (I assumes that is how you know it is divide by zero). Print the address and go look in your code. If you can print a stack trace it would be even easier to solve.
Another option would be to check the differences in your version control software between the last know working version and the first non working version. This should give you a limmited change set within which to search for the problem.

Why does Visual C++ not hit a breakpoint in, or step through a specific function?

I have the following:
classA::FuncA()
{
... code
FuncB();
... code
}
classA::FuncB(const char *pText)
{
SelectObject(m_hDC, GetStockObject ( SYSTEM_FONT));
wglUseFontBitmaps(m_hDC, 0, 255, 1000);
glListBase(1000);
glCallLists(static_cast<GLsizei>(strlen(pText)), GL_UNSIGNED_BYTE, pText);
}
I can hit breakpoints anywhere in FuncA. If I try to step into FuncB, it steps over. It will accept a breakpoint in FuncB, but never hits it. I know it is executing FuncB, because I can put a MessagBox() call in FuncB and get the message box.
I'm new to VS2005 after a few years away from extensive VC6 usage. The one situation like this I recall from my VC6 days, is if symbol information is not available. However, in this case both functions are in the same file, so the symbol information must be correct. Also in that case I think you couldn't even set the breakpoint.
I've tried all the silly voodoo like rebuilding the whole solution.
What stupid thing am I overlooking?
EDIT: Added code for FuncB in response to comment about it possibly being essentially inline-able. (It's just the exact sample code from MSDN for wglUseFontBitmaps [minus comments here]). I don't see how inlining that would impede stepping through each call.
Make sure all compiler optimizations are disabled (/Od). Compiler optimization can cause problems with debugger breakpoints.
Not sure what the problem is, but one thing you might try is to look at the disassembled code. You can switch betwen the source code and disassbled view with VS. I do not have the IDE in front of me at work, so the terms might be slightly off.
If you put the debugger into this mode, you can see what the assembly instructions that are executing. This helps sometimes to determine these kinds of problems. Sometimes, although not usually with a debug build, calls are optimized out by the compiler.
If everything fails try updating to VS2005 SP1 if you don't already have it...
Sounds strange indeed!
Thanks for posting the code. This is clearly not what I had guessed.
For posterity's sake, and to clear things up, my guess was that if (1) the function was one line and (2) the compiler inlined the function, then (3) the debugger might not know how to step into it. This guess relies on the fact that some debuggers do have trouble with inlined code and other compiler optimizations. I'm not familiar enough with Visual Studio's debugger to say whether it is on that list.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but will probably make other debuggers crash or refuse to read the program. ...
GCC allows you to use -g with -O. The shortcuts taken by optimized code may occasionally produce surprising results: some variables you declared may not exist at all; flow of control may briefly move where you did not expect it; some statements may not be executed because they compute constant results or their values were already at hand; some statements may execute in different places because they were moved out of loops.
The GCC manual used to have a statement that some compilers would refuse to emit debugging symbols in optimized code because their debuggers couldn't follow it.
actually i had a similar problem, found out the code wasnt getting compiled when i was running the program, so make sure you 'compile' the program before you try running it