How to pass arguments to a function while GDB - c++

I'm trying to use GDB to debug my C++ program.
I'm thinking if it's possible to pass arguments to a function while using GDB.
For example, I have such a program as below:
#include <iostream>
void func(int a)
{
std::cout << a << std::endl;
}
int main(int argc, char **argv)
{
func(2222);
return EXIT_SUCCESS;
}
I set a breakpoint at the line func(2222) in the function main. My question is: is it possible to set another argument to the function func, instead of 2222, while using GDB on this program?

You can change the value a inside the function func()).
For that you can use:
assign a = $value_you_want
Example
b func # set breakpoint
c # continue
assign a = 2 # breakpoint gets hit, change value from a = 222 to a = 2

Yes. You can evaluate expressions while debugging. You can use either call <expr> or print <expr>, but the expression must be known at the time of breakpoint.
In your example, you could do:
gdb ./test
(gdb) b main
...
(gdb) r
...
(gdb) call func(11)
11
More info about call/print: https://sourceware.org/gdb/onlinedocs/gdb/Calling.html

I don't think it's possible to change the value passed to the function before the call of func(2222). However, you are able to modify the values of the parameter after GDB has stepped into the function, before another code execution.
My favorite way to debug with GDB is within Visual Studio Code, it provides a GUI on top of all the GDB commands, and makes using advanced GDB debugging much easier. And you can set a new value for the variable simply by clicking on it. You can see an example below.

Related

can I debug my cpp code using linux gdb? if yes how can I keep break points on a function which is called over an object

example:
class test_gdb
{
public:
void testFun(void)
{
cout << "this is test function"<<endl;
}
};
int main(void)
{
test_gdb testObj;
testObj.testFun();
}
here if I want to keep a break point at testFun, how can I do it. I tried but with break testFun but it didn't work.
how can I do it
Several ways:
(gdb) break test_gdb::testFun
Set breakpoints on all testFuns, regardless of which class they are defined in:
(gdb) rbreak testFun
If you have several testFuns with different signatures (different parameter types), you can use GDB tab-completion to select one
(gdb) break 'test_gdb::testFun<TAB> # GDB will complete or offer multiple choice

Printing Symbols on the stack using GDB

I was trying to debug a program that has a corrupted stack and seems too big (it has multiple threads) to manually debug. So I was wondering if there was a way to print out the symbols that correspond to the addresses on the stack after the corruption to try and get a better idea of how it got there.
I noticed the "info symbol" command (which normally prints out the symbol at a given address) only accepts one address at a time. So, I tried to write a script to do what I wanted, but when I tried to store the addresses in convenience variables so I could iterate through the stack manually, the info symbol command wouldn't work.
I know on WinDBG there is the dds command which does what I'm looking for, but I have not been able to find an equivalent in GDB. Does anyone know an equivalent?
x command with a flag will decode memory as address and will try to lookup for the symbols
given code:
int func3(int a)
{
return a+a;
}
int func2(int b)
{
return func3(b+b);
}
int func1(int c)
{
return func2(c+c);
}
int main(int argc, char** argv)
{
return func1(argc);
}
and breakpoint at func3 output will be:
(gdb) x /16ga $rsp
0x7fffffffe150: 0x7fffffffe168 0x5555555545fa &ltfunc2+23&gt
0x7fffffffe160: 0x2000000c2 0x7fffffffe180
0x7fffffffe170: 0x555555554613 &ltfunc1+23&gt 0x100000000
0x7fffffffe180: 0x7fffffffe1a0 0x55555555462e &ltmain+25&gt
0x7fffffffe190: 0x7fffffffe288 0x100000000
0x7fffffffe1a0: 0x555555554630 &lt__libc_csu_init&gt 0x7ffff7a05b97 &lt__libc_start_main+231&gt
0x7fffffffe1b0: 0x1 0x7fffffffe288
0x7fffffffe1c0: 0x100008000 0x555555554615
This might not answer your question but could help you with identifying the place where you have the stack corruption. Have you tried compiling with -fstack-protectorxxx flags on ?
https://en.wikibooks.org/wiki/Linux_Applications_Debugging_Techniques/Stack_corruption

How to cout the return value of the main function "main()" in c++?

How to cout the return value of the main function "main()"? I just want to check if the return value of main function is really "0" when it is successfully executed.
Thank you!
You can use a unix command to check the return value of the previously executed command, in this case your c program.
echo $?
The shell variable $? is the return code of the previous command.
How to find the return value of last executed command in UNIX?
If you want to check the value within the code, just cout the value right before the return.
Do you mean you want to test that the following returns 0?
int main() {
int rc = doSomething();
return rc;
}
You can do it like this:
int main() {
int rc = doSomething();
std::cout << rc << "\n"; // Just print it out before returning
return rc;
}
But it's better to check the return value in the shell from where you run your application:
On UNIX/Linux (in shell):
> ./my_app
> echo $?
0
On Windows (in command prompt):
> my_app.exe
> echo %ERRORLEVEL%
Note that in C++ you are not allowed to intercept the call to main() or call it yourself.
3.6.1 Main function
The function main shall not be used within a program.
So you should not attempt to wrap the main() call and print its return value. Even if that works, it would not be portable (not to mention you'd actually end up running your application twice).
main is special, mostly because you can't call it yourself. The value that it returns is passed back to the operating system, which does whatever is appropriate. The C++ standard can't dictate how the OS treats various return values, so it provides an abstraction: you can use return EXIT_SUCCESS to indicate success, and you can use return EXIT_FAILURE to indicate failure. (You can also use return 0 to mean return EXIT_SUCCESS; the program's runtime system has to handle this correctly). The values of the macros EXIT_SUCCESS and EXIT_FAILURE are suitable for the OS that the program was compiled for. While 0 is the typical value for EXIT_SUCCESS, it's certainly possible for an OS to require a different value, and EXIT_SUCCESS will have the appropriate value for that OS. So even if you could check the value returned from main it wouldn't tell you much, without also knowing what value the OS expects from a successful program.
Type the other function after main(), then type main(); in that function
One problem though, main will be the first function to be called automatically. Although, i'm sure there is a way to fix it. This is how you call main or return main.
Hope this helps.
int main() {
int i = 5;
cout << i;
}
int second() {
main();
}
Welcome to Stack Overflow!
If it's 0, then it's 0. You are the one who specify the return value of your own function. If you are unsure, please add code and/or problem, which is bothering you.

debugging segmentation fault

I have a c++ program that compiles fine under gcc (4.8.1), icpc (13.1.3), clang++ (3.3) and runs okay except for the clang++ version which crashes with segfault. When I try to run this in the gdb or lldb debugger, I get EXC_BAD_ACCESS with address 0x0. The crash occurs in a member function of a helper class and the debugger claims that this has value 0x0. However going up one level, the pointer pimpl of the helper class is reported to have a non-null value and I can access its data, which look perfectly sensible.
here is some pseudo code (... is not the ellipse, but means "some parameters")
struct helper;
struct foo {
helper* pimpl;
foo(...);
void bar(...);
};
struct helper {
helper(...);
void hbar(...)
{
// crash here with *this = 0x0 according to debugger
}
};
foo::foo(...) : pimpl(new helper(...)) {}
void foo::bar(...)
{
pimpl->hbar(...); // pimpl NOT 0x0 according to debugger ??!
}
What could have gone wrong and how can I find out? Note: the question is NOT: "what is wrong with my code?"
edit 1 Perhaps it is worth mentioning that some of the arguments passed to helper::hbar() have been "optimised away by the compiler", according to the debugger, at the point of foo::bar()), while they have address 0x0 within helper::hbar()
edit 2 If I print out the value of this from within helper::hbar() the error does not occur.
edit 3 The error occurs with -O0 as well as -O2.
edit 4 The first arg of helper::hbar() was taken via const reference. If I change that to by value, everything works fine .... That argument was a spatial vector, similar to std::array<double,3>.
One way to do it - create a log file, print value of pimpl/some variable belonging to pimpl before
pimpl->hbar(...);,
and inside
pimpl->hbar(...);
Compare output from different compilers, try narrow down the problem that way adding more output to log file as you start seeing divergence...

main () returns an integer? [duplicate]

This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 9 years ago.
I am currently reading what functions are in c++. It says that they are "artifacts that enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing.A function, when invoked, typically returns a value to the calling function."
It then goes on to say that main() is recognized by the compiler as the starting point of your c++ application and has to return an int (integer).
I don't know what is meant by 'has to return an integer'. From my (extremely limited experience) int main () is the start of your application. But what is meant by 'has to return an int'?. This is also intertwined with me not understanding 'typically returns a value to the calling function'
Just like in mathematics, in C++ functions return values. All functions in C++ must specify exactly what type of value they return, and every function must return only one type of thing. In some cases, that "one type of thing" might be nothing, which is denoted in C++ with the keyword void.
Every function must declare what it returns. This is done via a function declaration. Here are several examples:
int foo();
void bar();
string baz();
int main();
4 function declarations. foo returns an int, bar returns nothing, baz returns a string (which is declared in the C++ Standard Library), and main returns an int.
Not only must every function declare what it returns, it must also return that type of thing. If your function returns void, then you can write:
void bar()
{
return;
}
...or just do nothing:
void bar()
{
}
If your function returns anything other than void, then you have to have a return statement that returns that type of thing:
int foo()
{
return 42;
}
If you declare a function to return one type of thing, but then try to return another type of thing, then either there must be a way to implicitly convert from whatever you're trying to convert to what the function is declared to return. If there is no possible implicit conversion, your program won't compile. Consider:
int foo()
{
return "foobar rulez!";
}
Here, foo is declared to return an int, but I'm trying to return a string (not a string from the Standard Library, but an old C-style const char* string. `"foobar rulez!" here is called a string literal.)
It is possible to write code to provide the implicit conversion I mentioned earlier, but unless you know exactly why you want to do that it's better to not get mixed up in all that right now.
What do you do with the values that are returned from functions? Again, just like with mathematics, you can use those values somewhere else in your program.
#include <cstdlib>
#include <iostream>
int foo()
{
return 42;
}
int main()
{
int answer = foo();
std::cout << "The answer to Life, the Universe and Everything is...\n"
<< answer << "!\n";
return 0;
}
Obviously you can't do anything with the value that is returned from a function that returns void, because a function that returns void doesn't really return anything at all. But these kinds of functions are useful for doing stuff kind of on the side.
#include <cstdlib>
#include <iostream>
int theAnswer = 0;
void DeepThought()
{
theAnswer = 42;
}
int foo()
{
return theAnswer;
}
int main()
{
DeepThought();
int answer = foo();
std::cout << "The answer to Life, the Universe and Everything is...\n"
<< answer << "!\n";
return 0;
}
OK, back to all this business with main.
main is a function in C++. There are a few things about main that make it special compared to other functions in C++, and two of those things are:
Every program must have exactly one function called main() (in global scope).
That function must return an int
There is one more thing about main that's a little special and possibly confusing. You don't actually have to write a return statement in main*, even though it is declared to return an int. Consider:
int main()
{
}
Note that there's no return statement here. That is legal and valid in C++ for main, but main is the only function where this is allowed. All other functions must have an explicit return statement if they don't return void.
So what about the return value from main()? When you run a program on an Windows or Linux computer, the program returns a value to the operating system. What that value means depends on the program, but in general a value of 0 means that the program worked without any problems. A value other than 0 often means that the program didn't work, and the exact value is actually a code for what went wrong.
Scripts and other programs can use these return values to decide what to do next. For example, if you wrote a program to rename an MP3 file based on the Artist and track Number, then your program might return 0 if it worked, 1 if it couldn't figure out the Artist, and 2 if it couldn't figure out the Track Number. You can call this function in a script that renames and then moves files. If you want your script to quit if there was an error renaming the file, then it can check these return values to see if it worked or not.
no explicit return statement in main: In cases where main does not have an explicit return, it is defined to return the value 0.
Although it may appear so when you are programming in C or C++, main is not actually the "first thing" that happens. Typically, somewhere in the guts of the C or C++ runtime library is a call to main, which starts your program. When your program is finished and returns from main, it will return a value (in C++, if you don't specify something, the compiler will automatically add return 0), and this return value is used to signal "the success" of the program.
In Unix/Linux etc, this is used as $?, so you can echo $? after running a program to see what the "result" was - 0 means "went well", other values are used for "failure". In windows, there is a ERRORLEVEL variable in batch scripts, etc, that can be used to see the result of the last command.
Edit: If your code calls another program, e.g. through CreatProcess in Windows, or fork()/exec() in a Unix style OS (or the C runtime functions spawn and siblings in almost any OS), the return value from main is the new process finishes, and made available for the owning process. End Edit.
Since, even in C++, main is a "C" style function, if you change the return type, it still has the same name, so the linker/compiler can't "detect" that it's got the wrong return type, and some weird stuff will happen if you declare void main(), std::string main() or float main() or something other than int main() - it will still compile, but what happens in the code calling main will be undefined behaviour - this means "almost anything can happen".
This is how you report back to the operating system the exit status of the program, whether it ran successfully or not. For example in Linux you can use the following command:
echo $?
to obtain the the exit status of the program that ran previously.
Yes, main should always returns an int, this can be used to show if the program runs successfully, usually 0 represents sucess, a non-zero value represents some kind of failure.
For example, in Linux, you can call your program in a bash script, and in this script, run different commands on the return status of your program.
It means, in the signature of main() the return type is int:
int main();
int main(int argc, char const *argv[]);
Now what value you would return from main(), is the question. Well, the return value is actually exit status which indicates to the runtime whether the main() executes sucessfully or unsuccessfully.
In Linux, I usually return EXIT_SUCCESS or EXIT_FAILURE depending on the cases. These are macros defined by <cstdlib>.
int main()
{
//code
if ( some failure condition )
return EXIT_FAILURE;
//code
return EXIT_SUCCESS;
}
As per the doc:
#define EXIT_SUCCESS /*implementation defined*/
#define EXIT_FAILURE /*implementation defined*/
The EXIT_SUCCESS and EXIT_FAILURE macros expand into an integral expression and indicate program execution status.
Constant Explanation
EXIT_SUCCESS successful execution of a program
EXIT_FAILURE unsuccessful execution of a program