I have the following example program that I want to debug:
#include <iostream>
#include <assert.h>
using namespace std;
int f(int x) {
assert(false); // something bad happens
return 2 * x;
}
int main() {
int a;
for (int i = 0; i < 5; i++) {
a++; // a is uninitialized
cout << a << endl;
}
cout << f(1) << endl;
}
This code has two problems:
- the variable
a
within the loop is uninitialized - the function
f
causes the program to crash
To detect these problems, I compile with g++ -Wall -Og -g source.cpp
and I get the following warning:
source.cpp: In function ‘int main()’:
source.cpp:17:10: warning: ‘a’ may be used uninitialized in this function [-Wmaybe-uninitialized]
17 | a++; // a is uninitialized
|
As this question shows, the flag -Og
(or any other optimization flag) is necessary for getting this warning.
When I debug the resulting executable with gdb
, it crashes (because of the assert statement) and the backtrace looks something like this:
[...]
#4 0x000055555555528f in f (x=<optimized out>) at source.cpp:7
#5 0x0000555555555322 in main () at source.cpp:21
As you can see, the variable x
has been optimized out. This happened because of the -Og
flag, as discussed in this question.
Obviously, I don't want this for debugging purposes. But when I remove the -Og
flag, the previously mentioned warning won't show up anymore. I now want to find a way to get this warning without having optimized out variables. Is this possible with g++
?
I am using g++
version 10.2.0 and gdb
version 9.2 on Ubuntu 20.10.