How to input unprintable ascii value in gdb when debugging a interacting program? - gdb

Since the value I am gonna input is unpredictable befor the program runs. So is there any way to input like "\x01\x02" in gdb?
The program I am debugging is a c program and the function in the program which needs an input is gets().
Any help would be appreciated! Thanks in advance!

the value I am gonna input is unpredictable befor the program runs
Assuming that you mean: "the value that needs to be read can only be determined while debugging the program with GDB", use named pipe as input (and standard GDB I/O redirection).

Related

SEGFAULT after inspecting variable with GDB on QtCreator

I have the following situation: My program runs fine, does all I want it to do, tests pass and Valgrind says it's all right. The only issue is the fact that if I pause execution at some point and try to inspect the state of some objects in the debug view of QtCreator (using GDB) some variables become <not-accessible> and, on resuming execution it reaches a segmentation fault.
To be a little more specific, the program is single threaded and this happens while following the pointers in a tree structure. The structure seems to be fine by the output of the tests.
Does anyone know about a possible cause? Maybe I have messed up with the stack in a way that luckily doesn't affect the tests or it may be just an IDE or debugger issue that should not care about? Thanks in advance for any answers.
Does anyone know about a possible cause?
Do you have multiple threads in your program?
When a program behaves differently depending on whether some GDB breakpoints are present or not, in 99.99% of the cases the program has a data race, and mere fact of stopping it at "inopportune" time exposes that fact.
On Linux, you could use Thread Sanitizer to check for data races.

how GDB knows it has to break at specified break point?

A basic question & I am very new to C/C++ and GDB.
We use GDB to debug a process. We attach GDB to a process and then specify filename.c along with line number to put break point.
My question is "How would GDB or OS OR possibly anything else know that it has to break at specified line number (in filename.c) after we connect GDB to running process?"
What is coming into picture that, say, the current process is run in debug mode and a breakpoint is applied and the process execution has to break (wait for user input) at that point?
The same way that if your program stops or crashes at a particular point, the debugger can tell you where in the program that point is.
For both of these to work the program binary must contain additional debugging information that associates addresses in the program image with locations in the source code (source file and line number.)
To add a breakpoint at a particular line the debugger finds the program address closest to that line, modifies the copy of the executable in memory to insert a special "break" instruction at that location which will cause the program's execution to be interrupted, then "traces" the program's execution and waits for it to reach the breakpoint and stop.
For more details see http://eli.thegreenplace.net/2011/01/23/how-debuggers-work-part-1/ and http://www.howzatt.demon.co.uk/articles/SimplePTrace.html
I can't comment for the latest version of gdb - but many debuggers actually swap the assembly instruction at the desired breakpoint location (in memory) with an interrupt instruction. This "wakes up" the debugger which takes control at this point.
Using a substituted interrupt instruction means that the CPU can execute your program at full speed and "trip up" at the desired location.
Modern processors are very complex, however, and probably have far superior debugging features.
GDB is aware of your code : it knows all about it. When you set a breakpoint at a line, GDB gets the equivalant machine instruction address : all your code (as machine instructions) is loaded in memory, so the instructions of your code have an address.
So now GDB knows the adress of the instruction you want to break. When you run your programm, GDB will use ptrace, which allow GDB to "see" each instructions before their execution. Then GDB have just to look if the current instruction (which will be executed) is the same as your instruction (that you want to break).

Incorrect Exit Code returned by Process.ExitCode Property

I have a native C++ application that I am running as a process during the execution of a C++/CLI application and I am seeing some strange behaviour with the exit code. I expect the exit code to be 0 when the process exits correctly but Process.ExitCode returns -529697949. However, when I debug the C++ application I can see that the exit code being returned is actually 0. Why would the Process.ExitCode property not match this value?
The absolute most important assumption to make when a program misbehaves is to never assume it is a bug in code that's used by hundreds of thousands of programmers and runs on half a billion machines. Assume it is a problem in your program first.
Armed with that knowledge, take a better look at the number. A good strategy when the number looks large and random is always to convert it hex. -529697949 = 0xe06d7363. Shazam, magic number, googles well too. That's the value of a Windows exception code. e0 makes it a fatal error, 6d7363 are ASCII codes that spell "msc".
Your program crashed on an unhandled C++ exception.

system("pause"); - Why is it wrong?

Here's a question that I don't quite understand:
The command, system("pause"); is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees.
Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it.
I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don't understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all?
What are your thoughts on this subject?
It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program.
Bodging in system("pause") runs the Windows command-line "pause" command and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output.
A better idea would be to put a breakpoint at the end and debug it, but that again has problems.
It's slow. It's platform dependent. It's insecure.
First: What it does. Calling "system" is literally like typing a command into the windows command prompt. There is a ton of setup and teardown for your application to make such a call - and the overhead is simply ridiculous.
What if a program called "pause" was placed into the user's PATH? Just calling system("pause") only guarantees that a program called "pause" is executed (hope that you don't have your executable named "pause"!)
Simply write your own "Pause()" function that uses _getch. OK, sure, _getch is platform dependent as well (note: it's defined in "conio.h") - but it's much nicer than system() if you are developing on Windows and it has the same effect (though it is your responsibility to provide the text with cout or so).
Basically: why introduce so many potential problems when you can simply add two lines of code and one include and get a much more flexible mechanism?
slow: it has to jump through lots of
unnecessary Windows code and a
separate program for a simple
operation
not portable: dependent on
the pause command
not good style:
making a system call should only be
done when really necessary
more
typing: system("pause") is longer
than getchar()
a simple getchar() should do just fine.
Using system("pause"); is Ungood Practice™ because
It's completely unnecessary.
To keep the program's console window open at the end when you run it from Visual Studio, use Ctrl+F5 to run it without debugging, or else place a breakpoint at the last right brace } of main. So, no problem in Visual Studio. And of course no problem at all when you run it from the command line.
It's problematic & annoying
when you run the program from the command line. For interactive execution you have to press a key at the end to no purpose whatsoever. And for use in automation of some task that pause is very much undesired!
It's not portable.
Unix-land has no standard pause command.
The pause command is an internal cmd.exe command and can't be overridden, as is erroneously claimed in at least one other answer. I.e. it's not a security risk, and the claim that AV programs diagnose it as such is as dubious as the claim of overriding the command (after all, a C++ program invoking system is in position to do itself all that the command interpreter can do, and more). Also, while this way of pausing is extremely inefficient by the usual standards of C++ programming, that doesn't matter at all at the end of a novice's program.
So, the claims in the horde of answers before this are not correct, and the main reason you shouldn't use system("pause") or any other wait command at the end of your main, is the first point above: it's completely unnecessary, it serves absolutely no purpose, it's just very silly.
In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.
Further explanation in this article.
You can use std::cin.get() from iostream:
#include <iostream> // std::cout, std::cin
using namespace std;
int main() {
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
Besides, system('pause') is slow, and includes a file you probably don't need: stdlib.h. It is platform-dependent, and actually calls up a 'virtual' OS.
Because it is not portable.
pause command is a windows / dos only program, so this your code won't run on linux/macOS. Moreover, system is not generally regarded as a very good way to call another program - it is usually better to use CreateProcess or fork or something similar.
As listed on the other answers, there are many reasons you can find to avoid this. It all boils down to one reason that makes the rest moot. The System() function is inherently insecure/untrusted, and should not be introduced into a program unless necessary.
For a student assignment, this condition was never met, and for this reason I would fail an assignment without even running the program if a call to this method was present. (This was made clear from the start.)
For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.
One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.
system("pause");
is wrong because it's part of Windows API and so it won't work in other operation systems.
You should try to use just objects from C++ standard library. A better solution will be to write:
cin.get();
return 0;
But it will also cause problems if you have other cins in your code. Because after each cin, you'll tap an Enter or \n which is a white space character. cin ignores this character and leaves it in the buffer zone but cin.get(), gets this remained character. So the control of the program reaches the line return 0 and the console gets closed before letting you see the results.
To solve this, we write the code as follows:
cin.ignore();
cin.get();
return 0;
It doesn't matter.
Adding a system("pause") or getchar() or std::cin.get() or whatever else you like at the end of a console program is there solely for the benefit of the programmer during development. The only purpose of such a line is to ensure that the console won't close before the programmer can view it, when executing the program from inside some IDE that likes to close the console when done executing.
That line will never make it to the production code executable, because why would anyone add "press any key to continue" at the end of a program executed from a console? That's not how sane console program UI works and they never have.
In general, using system() is bad practice but that's another story.
Here's one reason you shouldn't use it: it's going to piss off most anti-virus programs running on Windows if you're passing the program over to another machine because it's a security threat. Even if your program only consists of a simple cout << "hello world\n"; system("pause");
It's resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.
the pro's to using system("PAUSE"); while creating the small portions of your program is for debugging it yourself. if you use it to get results of variables before during and after each process you are using to assure that they are working properly.
After testing and moving it into full swing with the rest of the solution you should remove these lines. it is really good when testing an user-defined algorithm and assuring that you are doing things in the proper order for results that you want.
In no means do you want to use this in an application after you have tested it and assured that it is working properly. However it does allow you to keep track of everything that is going on as it happens. Don't use it for End-User apps at all.
Next to the arguments provided already (insecurity, slowness, non-portability, ...) there's yet another point missing:
If you are writing production tools of whatever kind then one should keep in mind:
Keeping an application window open is not the task of the application! Trying to do so by whatever means (system("pause");, getchar();, getch() or whatever else) is wrong by principle.
The application waiting for user input prevents it from being runable in any kind of scripting (bash script, windows batch file, ...), which is a pretty common use case – who should provide the user input there?
These problems would already start if your teacher tried to automise testing your programme with different inputs in his own script (obviously it doesn't...)!
Now if you are just playing around with any kind of testing code that you'll throw away anyway without having been seen by anywhere else (including your teacher) – who should care? Problem then, though, is that you will get used to such practices and will tend to use them even in places where you shouldn't. So best don't get used to right from the start...
It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.

How do I debug while running my program in Valgrind?

I was finishing up a code mod and wanted to run my program through Valgrind to make sure I've got all memory accounted for, but my program failed an assertion that doesn't fail when running on its own. Is it possible to stop in the debugger while running from Valgrind? I'm currently wading through the manual, but figured I could get my answer faster from you all.
I discovered the --db-attach=yes argument. This will stop every time an error is detected and ask if you want to enter the debugger at this point.
For my program, this is proving to be difficult to use, however. I read a file from standard input for initialization, and I think Valgrind is interpreting EOLs as responding to its prompts.