Initialize memory with nan in C++ for debugging - c++

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...

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.

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

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();

Related

is null value is equal to zero(0)? [duplicate]

This question already has answers here:
C++: Uninitialized variables garbage
(5 answers)
Closed 4 years ago.
A programmer told me that if we don't assign a value to any variable e.g like max then it consider as null value.
{
int max=0,x[5];
for(int a=0;a<5;a++)
{
cout<<"Enter no "<<a+1<<" : ";
cin>>x[a];
if(max<x[a])
{
max=x[a];
}
}
cout<<endl<<max;
}
output:
Enter no 1 : 1
Enter no 2 : 5
Enter no 3 : 8
Enter no 4 : 7
Enter no 5 : 5
8
and when type max=0 means at the declaration assign 0 to max
it gives me the same result that's mean null value is equal to 0.
if yes then what is difference between null value and 0
It actually depends on what programming language are you writing your code in.
For instance, if you access in read an uninitialized variable in c/c++ you cannot know which value it will give you.
Memory is not zero-ed when the variable is allocated, so whatever bits were there, they will be read as a value in the type of that variable.
Game Maker's own language, GML, allows you to decide at compile time if uninitialized variables have to be set to 0 by default or not; but any decent programmer would set that option off and not rely on it; i'm not aware of other languages that automatically initialize variable values.
I'd say relying on such a feature is bad practice.
About the difference between null and 0, it actually depends on the base type of your variable.
An integer can only store integers, so null will still be readable as an integer.
If you default initialize a fundamental-type object (such as int) in automatic storage, the value will be indeterminate. The behaviour of reading an indeterminate value is undefined.
Undefined behaviour means that the standard doensn't constrain the behaviour of the program in any way. As far as the C++ standard is concerned, possible behaviours include, none which are guaranteed:
Output that you expect.
Output that you don't expect.
Same output as some program which doesn't have UB.
Different output than some program which doesn't have UB.
Any output.
No output whatsoever.
Side-effects that you expect.
Side-effects that you don't expect.
Any Side-effects.
No Side-effects whatsoever.
Possible side-effects include:
Corruption of data.
Security vulnerabilities.
Anything within the capability of the process, hopefully limited by the OS.
Inconsistent behaviour on other systems.
Inconsistent behaviour even on same system if you re-compile using another compiler.
Inconsistent behaviour even if you re-compile using same compiler.
Inconsistent behaviour even without recompilation during another execution:
Possibly only when you're on vacation.
Possibly only when you're demonstrating your program to your employer or important client.
Consistent behaviour in all of the above cases.
A programmer told me that if we don't assign a value to any variable e.g like max then it consider as null value.
There is no such thing as null value integer in C++. There is such thing as a null pointer, as well as null character, neither of which are directly related to each other, and neither have anything to do with an uninitialized variable.
Your programmer is using confusing terminology, but if by null value, they meant indeterminate value, then they are correct. And in that case your question becomes what is difference between indeterminate value and 0, and the answer is that reading an indeterminate value is undefined behaviour (see above).
when type max=0 means at the declaration assign 0 to max
To be pedantic, you have int max=0 which is not an assignment, but initialization.
There's no 'null' value in c++. Local primitives are uninitialized (you'll get garbage that just happens to be in memory at this time), while static and global variables are zero-initialized. So by saying int max; You'll either get random garbage or zero (depending on where you declared it).

Fortran : Initialize all variables to a specific default value

I am working on a ~40 years old Fortran spaghetti code with lots of variables that are implicitly declared. So there is not a simple way to even know what variables exist in the code in order to initialize their values. Now, is there a way to tell the compiler (for example Intel Fortran) to initialize all variables in the code to a specific default value (e.g., -999) other than zero or a very large number, as provided by Intel compiler?
gfortran provides some options for this. Integers can be intialized with -finit-integer=n where n is an integer. For real numbers you can use -finit-real=<zero|inf|-inf|nan|snan>. Together with -ffpe-trap=denormal this can be very helpful, to get uninitialized reals.
You probably want :
ifort -check uninit
Note per the man page this only checks scalars
Also, based on some quick testing it is a pretty weak check. It doesn't catch this simple thing for example:
program test
call f(i)
end
subroutine f(j)
write(*,*)j
end
returns 0 ..
I suppose its better than nothing though.

Initialize a variable

Is it better to declare and initialize the variable or just declare it?
What's the best and the most efficient way?
For example, I have this code:
#include <stdio.h>
int main()
{
int number = 0;
printf("Enter with a number: ");
scanf("%d", &number);
if(number < 0)
number= -number;
printf("The modulo is: %d\n", number);
return 0;
}
If I don't initialize number, the code works fine, but I want to know, is it faster, better, more efficient? Is it good to initialize the variable?
scanf can fail, in which case nothing is written to number. So if you want your code to be correct you need to initialize it (or check the return value of scanf).
The speed of incorrect code is usually irrelevant, but for you example code if there is a difference in speed at all then I doubt you would ever be able to measure it. Setting an int to 0 is much faster than I/O.
Don't attribute speed to language; That attribute belongs to implementations of language. There are fast implementations and slow implementations. There are optimisations assosciated with fast implementations; A compiler that produces well-optimised machine code would optimise the initialisation away if it can deduce that it doesn't need the initialisation.
In this case, it actually does need the initialisation. Consider if scanf were to fail. When scanf fails, it's return value reflects this failure. It'll either return:
A value less than zero if there was a read error or EOF (which can be triggered in an implementation-defined way, typically CTRL+Z on Windows and CTRL+d on Linux),
A number less than the number of objects provided to scanf (since you've provided only one object, this failure return value would be 0) when a conversion failure occurs (for example, entering 'a' on stdin when you've told scanf to convert sequences of '0'..'9' into an integer),
The number of objects scanf managed to assign to. This is 1, in your case.
Since you aren't checking for any of these return values (particular #3), your compiler can't deduce that the initialisation is necessary and hence, can't optimise it away. When the variable is uninitialised, failure to check these return values results in undefined behaviour. A chicken might appear to be living, even when it is missing its head. It would be best to check the return value of scanf. That way, when your variable is uninitialised you can avoid using an uninitialised value, and when it isn't your compiler can optimise away the initialisations, presuming you handle erroneous return values by producing error messages rather than using the variable.
edit: On that topic of undefined behaviour, consider what happens in this code:
if(number < 0)
number= -number;
If number is -32768, and INT_MAX is 32767, then section 6.5, paragraph 5 of the C standard applies because -(-32768) isn't representable as an int.
Section 6.5, paragraph 5 says:
If an exceptional condition occurs during the evaluation of an
expression (that is, if the result is not mathematically defined or
not in the range of representable values for its type), the behavior
is undefined.
Suppose if you don't initialize a variable and your code is buggy.(e.g. you forgot to read number). Then uninitialized value of number is garbage and different run will output(or behave) different results.
But If you initialize all of your variables then it will produce constant result. An easy to trace error.
Yes, initialize steps will add extra steps in your code at low level. for example mov $0, 28(%esp) in your code at low level. But its one time task. doesn't kill your code efficiency.
So, always using initialization is a good practice!
With modern compilers, there isn't going to be any difference in efficiency. Coding style is the main consideration. In general, your code is more self-explanatory and less likely to have mistakes if you initialize all variables upon declaring them. In the case you gave, though, since the variable is effectively initialized by the scanf, I'd consider it better not to have a redundant initialization.
Before, you need to answer to this questions:
1) how many time is called this function? if you call 10.000.000 times, so, it's a good idea to have the best.
2) If I don't inizialize my variable, I'm sure that my code is safe and not throw any exception?
After, an int inizialization doesn't change so much in your code, but a string inizialization yes.
Be sure that you do all the controls, because if you have a not-inizialized variable your program is potentially buggy.
I can't tell you how many times I've seen simple errors because a programmer doesn't initialize a variable. Just two days ago there was another question on SO where the end result of the issue being faced was simply that the OP didn't initialize a variable and thus there were problems.
When you talk about "speed" and "efficiency" don't simply consider how much faster the code might compile or run (and in this case it's pretty much irrelevant anyway) but consider your debugging time when there's a simple mistake in the code do to the fact you didn't initialize a variable that very easily could have been.
Note also, my experience is when coding for larger corporations they will run your code through tools like coverity or klocwork which will ding you for uninitialized variables because they present a security risk.

Default value of an integer?

My program requires several floats to be set to a default number when the program launches. As the program runs these integers will be set to their true values. These true values however can be any real number. My program will be consistently be checking these numbers to see if their value has been changed from the default.
For example lets say I have integers A,B,C. All these integers will be set to a default value at the start (lets say -1). Then as the program progresses, lets say A and B are set to 3 and 2 respectfully. Since C is still at the default value, the program can conclude than C hasn't been assigned a non-default value yet.
The problem arises when trying to find a unique default value. Since the values of the numbers can be set to anything, if the value its set to is identical to the default value, my program won't know if a float still has the default value or its true value is just identical to the default value.
I considered NULL as a default value, but NULL is equal to 0 in C++, leading to the same problem!
I could create a whole object consisting of an bool and a float as members, where the bool indicates whether the float has been assigned its own value yet or not. This however seems like an overkill. Is there a default value I can set my floats to such that the value isn't identical to any other value? (Examples include infinity or i)
I am asking for C/C++ solutions.
I could create a whole object consisting of an bool and a integer as
members, where the bool indicates whether the number has been assigned
its own value yet or not. This however seems like an overkill.
What you described is called a "nullable type" in .NET. A C++ implementation is boost::optional:
boost::optional<int> A;
if (A)
do_something(*A);
On a two's complement machine there's an integer value that is less useful than the others: INT_MIN. You can't make a valid positive value by negating it. Since it's the least useful value in the integer range, it makes a good choice for a marker value. It also has an easily recognizable hex value, 0x80000000.
There is no bit pattern you can assign to an int that isn't an actual int. You need to keep separate flags if you really have no integer values that are out of bounds.
If the domain of valid int values is unlimited, the only choice is a management bit indicating whether it is assigned or not.
But, are you sure MAX_INT is a desired choice?
There is no way to guarantee that a value you assign an int to is not going to be equal to another random int. The only way to assure that what you want to happen occurs, is to create a separate bool to account for changes.
No, you will have to create your own data type which contains the information about whether it has been assigned or not.
If as you say, no integer value is off limits, then you cannot assign a default "uninitialised" value. Just use a struct with an int and a bool as you suggest in your question.
I could create a whole object consisting of an bool and a integer as
members, where the bool indicates whether the number has been assigned
its own value yet or not. This however seems like an overkill.
My first guess would be to effectively use a flag and mark each variable. But this is not your only choice of course.
You can use pointers (which can be NULL) and assign dynamically the memory. Not very convenient.
You can pick a custom value which is almost never used. You can then define this value to be the default value. Ofc, some time, you will need to assign this value to your floats, but this case won't happen often and you just need to keep track of this variables. Given the occurrence of such case, a simple linked list should do.

Unitialized int value always the same (C++)

Given this code:
void main()
{
int x;
cout << x;
system("pause");
}
When I debug this piece of code, it always prints -858993460A. I read that its because VS set this as default value for Unitialized vars. But I also read that in release mode, this should get random value. But everytime I run this code in release mode I get 1772893972A , which Is not changing -> its not random. What is this? Why do I get this value?
Your confusion is in the assumption that "in release mode, this should get a random value." That is not true.
An uninitialized variable gets an "undefined" value. It could be random, but it doesn't have to be.
If you want x to have a random value, then use rand().
The main is not the real entrypoint of the executable, in general the real entrypoint is taken by the runtime library (and in VC++ is definitely like that), which performs some CRT initialization tasks and then calls your main. That value is probably a leftover of one of the function calls performed by the initialization code; the difference between the Debug and Release builds is probably due to different initialization/stack management between the two configurations. By the way, it's just a chance that such vales are always the same, probably they are from some parameter/variable that assumes the same value every time.
If it's not like that, it's probably stuff from some other initialization task internal to your process. It's not stuff from other processes or that just "happened" to be at that spot in physical memory, since Windows (on which your application is running) never gives memory pages that belonged to other processes without first blanking them.
Still, keep in mind that, as far as the standard is concerned, uninitialized variables have "indeterminate initial value" (§3.3.1 ¶9), so you should not rely on the values you may get by reading uninitialized variables. If you need random numbers, use the appropriate library functions.
I was forgetting... void main is not valid C++, it should be int main (§3.6.1 ¶2, "It shall have a return type of type int").
Interestingly, your DEBUG value in hex is 0xFFFFFFFFCCCCCCCC. Your RELEASE value in hex is just random. It could be that the debug compile adds a stack scribbler to make sure your uninitialized values are not sane (like 0) and would be quickly noticeable.