Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize memory with nan in C++ for debugging

How would I initialize all memory in a c or c++ program to NaN (Not-A-Number) at startup for debugging with gdb?

I believe by default gdb initializes with zeros, but this is often not helpful for finding code that crashes due to initialization error.

PS: I want to initialize every variable and array as NAN (or some garbage) for debugging only. The program I am working with has thousands of variables, so rather tedious to change every one...

like image 913
brain Avatar asked Oct 29 '14 02:10

brain


3 Answers

Those hex numbers might be correct in Rafael's post, but I would recommend a more semantic way.

See http://en.cppreference.com/w/cpp/types/numeric_limits/quiet_NaN

#include <limits>
double nan1 = std::numeric_limits<double>::quiet_NaN();
double nan2 = std::numeric_limits<double>::signaling_NaN();

Note that there are two kinds of NaN.

like image 134
Notinlist Avatar answered Nov 01 '22 07:11

Notinlist


You can cast your floats to 32-bit ints and set them to any number between

0x7FC00000 and 0x7FFFFFFF or 
0xFFC00000 and 0xFFFFFFFF

For doubles cast to u64 and set them to any number between

0x7FF8000000000000 and 0x7FFFFFFFFFFFFFFF or 
0xFFF8000000000000 and 0xFFFFFFFFFFFFFFFF
like image 24
Rafael Baptista Avatar answered Nov 01 '22 06:11

Rafael Baptista


What do you mean by "initialize all memory"? This is probably only possible on some bare metal embedded system, not in Linux. And even there gdb does nothing like that.

Each program has two relevant special memory regions: one is zero initialized, which of course needs to be filled by zeros. This variables are allocated withing region marked as such and their value is not stored in executable. Other is initialized to some explicitly defined value. These values are stored within executable.

While it should be possible to get boundaries of this region (just like C library code does), the question is, why would you want to fill zero initialized region with NaNs. It would cause unwanted side-effects elsewhere in your code. For example, if you have some global int that is initialized to 0, filling this region with NaNs would also change the initial value of that integer to something entirely unexpected.

If you need some variables or array initialized to NaN, just initialize variables appropriately when declaring them (as explained by Notinlist and Rafael). You could use some macro(s), if you really don't want to repeat that ugly long statement every time, something like

#define NaNdouble(X) double X = std::numeric_limits<double>::quiet_NaN();
like image 39
dbrank0 Avatar answered Nov 01 '22 06:11

dbrank0