uninitialized local variable - c++

This code compiles and runs though gives a Microsoft compiler error that I cant fix
warning C4700: uninitialized local variable '' used.
This is in the last line of the code, I think
#include <iostream>
using namespace std;
const int DIM0 = 2, DIM1 = 3, DIM2 = 4, DIM3 = 5;
void TestDeclar();
int main(){
TestDeclar();
cout << "Done!\n";
return 0;
}
void TestDeclar(){
//24 - array of 5 floats
float xa[DIM3], xb[DIM3], xc[DIM3], xd[DIM3], xe[DIM3], xf[DIM3];
float xg[DIM3], xh[DIM3], xi[DIM3], xj[DIM3], xk[DIM3], xl[DIM3];
float xm[DIM3], xn[DIM3], xo[DIM3], xp[DIM3], xq[DIM3], xr[DIM3];
float xs[DIM3], xt[DIM3], xu[DIM3], xv[DIM3], xw[DIM3], xx[DIM3];
//6 - array of 4 pointers to floats
float *ya[DIM2] = {xa, xb, xc, xd}, *yb[DIM2] = {xe, xf, xg, xh};
float *yc[DIM2] = {xi, xj, xk, xl}, *yd[DIM2] = {xm, xn, xo, xp};
float *ye[DIM2] = {xq, xr, xs, xt}, *yf[DIM2] = {xu, xv, xw, xx};
//2 - array of 3 pointers to pointers of floats
float **za[DIM1] = {ya, yb, yc};
float **zb[DIM1] = {yd, ye, yf};
//array of 2 pointers to pointers to pointers of floats
float ***ptr[DIM0] = {za, zb};
cout << &***ptr[DIM0] << '\n';
}

You're accessing past the end of the ptr4D. DIM0 is 2, one greater than the last index of 1!
Change the last few lines to:
//array of 2 pointers to pointers to pointers of floats
float ***ptr4D[DIM0] = {za, zb};
cout << &***ptr4D[0] << '\n';

Not sure if I can help you but I tried to find out what's wrong trying to run it on my linux machine. I've compiled it on a ubuntu machine to compare and it went ok, even tellign the compiler to turn on all option warnings (passing the -Wall option). When running, I got this:
# Compiled it with -Wall to enable all warning flags and -g3 to produce extra debug information
~$ g++ -Wall stackoverflow.cpp -g3
./a.out
Segmentation fault (core dumped)
Then I've tried to debug it with GDB (GNU debugger) and got this:
(gdb) r
Starting program: /home/ubuntu/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400986 in TestDeclar () at stackoverflow.cpp:34
34 cout << &***ptr4D[DIM0] << '\n';
(gdb) s
So it appears that the problem is at the cout line. Checking your code again, DIM0's value is 2, so you're trying to access a memory address beyond the ptr4D. As user1721424 mentioned, just replace the DIM0 with 0 and it's done!
#After fixing it:
~$ ./a.out
0x7fff74cd3830
Done!
Hope it helps!

Related

Error when using gdb, throwing SIGSEGV when there shouldn't be

I'm having this simple c++ code:
int main() {
int x = 1;
int y = 2;
int z = x + y;
return 0;
}
Then I do g++ -g main.cpp -o main, then gdb main into gdb mode. Then I set break point by b 2, then r, then type n, immedately I get
Program received signal SIGSEGV, Segmentation fault.
0x000055555555513a in main () at main.cpp:4
4 int z = x + y;
I am very confused as this code is too simple and having nothing wrong.
Could somebody help? Thank you so much!
When I input backtrace, I got
#0 0x000055555555513a in main () at main.cpp:4
I don't know in which way it is incorrect.
If I set break point b 4, then r, then the program safely comes to line 4, but same thing happens if I use n. Very confused.
I'm running it in Debian virtual box but I don't think it's related.

Printing structure varibales at a particular point

Lets say we have a structure with some variables.
Is it possible to values of those variables at a particular point of execution..?
One way might be to print each of them individually.
But my point is, is there a way to check values of all the variables in that structure at a particular point of time, without having to use printf or cout to print each variable value..?
Just wondering if this is possible atleast in gdb..!!
it is possible in gdb, no problem:
For example:
x.C
#include <iostream>
struct A {
int x;
int y;
};
int main(int argc,char **argv) {
A a;
a.x=10;
a.y=11;
std::cout << "Hello world" << std::endl;
}
compiling:
g++ -g -o x x.C
running on gdb
gdb x
(gdb) break main
Breakpoint 1 at 0x40096c: file x.C, line 10.
(gdb) run
Starting program: /home/jsantand/x
Breakpoint 1, main (argc=1, argv=0x7fffffffde98) at x.C:10
10 a.x=10;
(gdb) next
11 a.y=11;
(gdb) next
12 std::cout << "Hello world" << std::endl;
(gdb) print a
$1 = {x = 10, y = 11}
(gdb) quit
Doing that on your code, traces, etc... it will be be more difficult as C++ lacks reflection.
You could do it by hand or if you're adventurous, create something to generate automatically operator<< for your classes an structs/classes so that they provide a string representation. You need some basic C++ parser at least.

View print methods in GDB

I have a complicated class for which I have written a clean printing method, more-or-less explicitly for the purposes of debugging. However, I can't seem to figure out the syntax to actually use it to print when I'm using gdb. Basically I want to be able to type something like "myObject->print()" and have it run my print method but instead I get the following error:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x00000000000000a1
0x00007fff814c0684 in std::ostream::sentry::sentry () The program
being debugged was signaled while in a function called from GDB. GDB
remains in the frame where the signal was received. To change this
behavior use "set unwindonsignal on" Evaluation of the expression
containing the function (wfSamplePath::print_traj(std::ostream&)) will
be abandoned.
where "wfSamplePath" is my class and "print_traj" is my print method (with std::cout as the default argument). So clearly something is wrong with how I think I can do this. I'm using gdb from within xcode 3. "myObject" is definitely in scope, as I can access some of its other methods.
The expression evaluator in GDB is quite limited, particularly with C++ expressions, so try to keep it simple. Particularly, do not use default arguments. Using cout is also probably a bad idea. So are inline functions.
I've got good results with a simple member function that returns a string. For example this code works as expected:
#include <sstream>
struct S
{
int x, y, z;
std::string debug();
};
std::string S::debug()
{
std::ostringstream os;
os << x << ", " << y << ", " << z;
return os.str();
}
int main()
{
S s;
s.x = 1;
s.y = 2;
s.z = 3;
return 0;
}
Then, compile and debug with:
$ g++ -O0 -g test.cpp
$ gdb ./a.out
....
$start
....
19 s.x = 1;
(gdb) n
20 s.y = 2;
(gdb) n
21 s.z = 3;
(gdb) n
22 return 0;
(gdb) p s.debug()
$1 = "1, 2, 3"

openmp segmentation fault - strange behaviour

I'm quite new at c++ and openmp in general. I have a part of my program that is causing segmentation faults in strange circumstances (strange to me at least).
It doesn't occur when using the g++ compiler, but does with intel compiler, however there are no faults in serial.
It also doesnt segfault when compiling on a different system (university hpc, intel compiler), but does on my PC.
It also doesn't segfault when three particular cout statements are present, however if any one of them is commented out then the segfault occurs. (This is what I find strange)
I'm new at using the intel debugger (idb) and i don't know how to work it properly yet. But i did manage to get this information from it:
Program received signal SIGSEGV
VLMsolver::iterateWake (this=<no value>) at /home/name/prog/src/vlmsolver.cpp:996
996 moveWakePoints();
So I'll show the moveWakePoints method below, and point out the critical cout lines:
void VLMsolver::moveWakePoints() {
inFreeWakeStage =true;
int iw = 0;
std::vector<double> wV(3);
std::vector<double> bV(3);
for (int cl=0;cl<3;++cl) {
wV[cl]=0;
bV[cl]=0;
}
cout<<"thanks for helping"<<endl;
for (int b = 0;b < sNumberOfBlades;++b) {
cout<<"b: "<<b<<endl;
#pragma omp parallel for firstprivate(iw,b,bV,wV)
for (int i = 0;i< iteration;++i) {
iw = iteration -i - 1;
for (int j = 0;j<numNodesY;++j) {
cout<<"b: "<<b<<"a: "<<"a: "<<endl;
double xp = wakes[b].x[iw*numNodesY+j];
double yp = wakes[b].y[iw*numNodesY+j];
double zp = wakes[b].z[iw*numNodesY+j];
if ( (sFreeWake ==true && sFreezeAfter == 0) || ( sFreeWake==true && iw<((sFreezeAfter*2*M_PI)/(sTimeStep*sRotationRate)) && sRotationRate != 0 ) || ( sFreeWake==true && sRotationRate == 0 && iw<((sFreezeAfter*sChord)/(sTimeStep*sFreeStream)))) {
if (iteration>1) {
getWakeVelocity(xp, yp, zp, wV);
}
getBladeVelocity(xp, yp, zp, bV);
} else {
for (int cl=0;cl<3;++cl) {
wV[cl]=0;
bV[cl]=0;
}
}
if (sRotationRate != 0) {
double theta;
theta = M_PI/2;
double radius = sqrt(pow(yp,2) + pow(zp,2));
wakes[b].yTemp[(iw+1)*numNodesY+j] = cos(theta - sTimeStep*sRotationRate)*radius;
wakes[b].zTemp[(iw+1)*numNodesY+j] = sin(theta - sTimeStep*sRotationRate)*radius;
wakes[b].xTemp[(iw+1)*numNodesY+j] = xp + sFreeStream*sTimeStep;
} else {
std::vector<double> fS(3);
getFreeStreamVelocity(xp, yp, zp, fS);
wakes[b].xTemp[(iw+1)*numNodesY+j] = xp + fS[0] * sTimeStep;
wakes[b].yTemp[(iw+1)*numNodesY+j] = yp + fS[1] * sTimeStep;
wakes[b].zTemp[(iw+1)*numNodesY+j] = zp + fS[2] * sTimeStep;
}
wakes[b].xTemp[(iw+1)*numNodesY+j] = wakes[b].xTemp[(iw+1)*numNodesY+j] + (wV[0]+bV[0])*sTimeStep;
wakes[b].yTemp[(iw+1)*numNodesY+j] = wakes[b].yTemp[(iw+1)*numNodesY+j] + (wV[1]+bV[1])*sTimeStep;
wakes[b].zTemp[(iw+1)*numNodesY+j] = wakes[b].zTemp[(iw+1)*numNodesY+j] + (wV[2]+bV[2])*sTimeStep;
} // along the numnodesy
} // along the iterations i
if (sBladeSymmetry) {
break;
}
}
}
The three cout lines at the top are what I added, and found the program worked when i did.
On the third cout line for example, if I change it to:
cout<<"b: "<<"a: "<<"a: "<<endl;
i get the segfault, or if I change it to:
cout<<"b: "<<b<<endl;
, i also get the segfault.
Thanks for reading, I appreciate any ideas.
As already stated in the previous answer you can try to use Valgrind to detect where your memory is corrupted. Just compile your binary with "-g -O0" and then run:
valgrind --tool=memcheck --leak-check=full <binary> <arguments>
If you are lucky you will get the exact line and column in the source code where the memory violation has occurred.
The fact that a segfault disappears when some "printf" statements are added is indeed not strange. Adding these statements you are modifying the portion of memory the program owns. If by any chance you are writing in a wrong location inside an allowed portion of memory, then the segfault will not occurr.
You can refer to this pdf (section "Debugging techniques/Out of Bounds") for a broader explanation of the topic:
Summer School of Parallel Computing
Hope I've been of help :-)
try increasing stack size,
http://software.intel.com/sites/products/documentation/hpc/composerxe/en-us/cpp/lin/optaps/common/optaps_par_var.htm
try valgrind
try debugger

Why does gdb show two different returns?

Last week I was a debugging a code and a weird situation came up: gdb passes through two different return clauses. I made a simple example that illustrates the situation:
#include <iostream>
using namespace std;
int test() {
string a = "asd";
string b = "asd";
while (true) {
if (a == b) {
return 0;
}
}
return -1;
}
int main() {
int result = test();
cout << "result: " << result << endl;
}
When debugging the code I got:
(gdb) b main
Breakpoint 1 at 0x1d4c: file example.cpp, line 19.
(gdb) r
Starting program: /Users/yuppienet/temp/a.out
Reading symbols for shared libraries +++. done
Breakpoint 1, main () at example.cpp:19
19 int result = test();
(gdb) s
test () at example.cpp:7
7 string a = "asd";
(gdb) n
8 string b = "asd";
(gdb) n
11 if (a == b) {
(gdb) n
12 return 0;
(gdb) n
15 return -1;
(gdb) n
16 }
(gdb) n
main () at example.cpp:20
20 cout << "result: " << result << endl;
(gdb) n
result: 0
21 }
(gdb) n
0x00001ab2 in start ()
I noted that even if gdb shows line 15, the return value is 0 (the finish command confirms this as well).
So the question is: why does gdb show line 15: return -1, even if the function is not really returning this value?
Thanks!
Edit:
I forgot to mention that I compiled with the following line:
g++ -Wall -pedantic -g -pg example.cpp
I suspect you're seeing the function epilogue. Your two strings have destructors, which are being implicitly called on return. Check out what the disassembly says to be sure, but I suspect that both return statements are mapping to something along the lines of:
stash return_value;
goto epilogue;
and correspondingly:
epilogue:
destroy a; // on the stack, so destructor will be called
destroy b;
really_return(stashed value);
The epilogue appears to come from line 15 as a side-effect of how g++ does line numbering - a fairly simple format, really just a list of tags of the form "address X comes from line number Y" - and so it's reporting 15 as the closest match. Confusing in this case, but correct a lot of the time.
Probably because the program counter register passes through the instructions that best map to the final return, i.e. the function's exit sequence. The actual return value is probably kept in a register, so the first return just loads the proper value and jumps to the end of the function, and then that address is "back-mapped" to the source code line of the final return.
You don't say, but if you compiled with optimization that is exactly the kind of behavior you would see in gdb. You see the first line setting up the return value, and then it jumps to the real return instruction but in C++ you see the entire thing including the return value.