danteDev danteDev - 1 year ago 84
C Question

purpose of uninitialize a variable

I come across an example of a function as below:

int someFunction(void)
int i;

for(i = 0; i < 10; i++)
a_var[i] = 0xFFFF; //uninitialize a_var

return 0;

What is the purpose of uninitialize a variable and why is it have to use 0XFFFF?

Answer Source

As said by others, there is no such thing as "un-initialising" a variable. That comment is misleading.

What the author probably meant is: let's initialise it with a value that clearly stands out (for example in the debugger) and that is not meant to be used by a program that runs correctly; instead, it is meant to be overwritten when the proper initialisation takes place. If the program crashes and the debugger shows the value is still 0xFFFF, it means the variable hasn't been initialised properly (otherwise it would have a different value), and then you know your code is accessing it at the wrong time, before the "correct" initialisation.

This technique is applied by Visual Studio when debugging C++ code: the variables are all automatically initialised with special values, chosen to be easy to see and remember. Examples include 0xABABABAB, 0xABADCAFE and 0xDEADDEAD. You can find more here and here. Wikipedia has a much longer list.

The author of this program is probably trying to replicate it. A better comment would be: "Initialise a_var with a known wrong value that helps detecting improper early accesses to it".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download