Initialize all variables, always - c

I am reading the FreeBSD coding style and am quite liking it (as I like vertically compact code). There is however this:
Initialize all Variables
You shall always initialize variables. Always. Every time. gcc with the flag -W may catch operations on uninitialized variables, but
it may also not.
Justification
More problems than you can believe are eventually traced back to a pointer or variable left uninitialized.
When there is no appropriate initial value for a variable, isn't it much better to leave it without a value. That way the compiler will probably catch reading it uninitialized. i am not talking about T *p = NULL, which is a trap representation and might (or may not) be quite useful, but rather int personal_number = 0 /* but 0 is a valid personal number!!*/
To clarify, in response to abasu's comment, my example is trying to illustrate cases when there are no available invalid values. I have asked a question and was answered that using impossible values to mark errors or other conditions is awesome. But it is not always the case. Examples are plentiful: 8bit pixel value, velocity vector, etc.
One valid alternative to "Always initialize variables", that I can see is:
//logical place for declarations
T a;
/*code, for example to set up the environment for evaluating a*/
a = fooForA();
/*more code*/
fooThatUsesA(a);
This way if initialization is forgotten, there will be warning and the bug will be fixed, removing the warning.

Are all integers valid personal numbers?
If not, then use an invalid value to initialize personal_number.
If they are, then even when you have not initialized personal_number yourself it still holds a value that is a valid personal number -- but that value is unknown. So initialize it to 0 anyway -- you have not introduced a problem (valid number before, valid number after), the only difference is that the number is now known to you.
Of course in both cases it would be better to not use an integer literal for initialization, but rather do something like this:
enum { INVALID_PERSONAL_NUMBER = -1 }
int personal_number = INVALID_PERSONAL_NUMBER;

Compilers often don't catch reading variables uninitialized. Instead, they're likely to use that information to make assumptions about the rest of the code to perform optimization, possibly introducing new and worse bugs:
int get_personal_number(const char *name)
{
int personal_number;
if (name != NULL) {
/* look up name in some array */
personal_number = ...
}
return personal_number;
}
An optimising compiler will infer that name cannot be NULL and eliminate the check. Similar issues have caused security bugs; see e.g. http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
Instead, rewrite your functions to initialize variables with their eventual correct value at declaration; this may require writing lots of small functions, using ternary expressions etc., which is generally better style anyway.

When there is no appropriate initial value for a variable, isn't it much better to leave it without a value.
In my opinion yes. Modern compilers are pretty good at catching uninitialised variable errors and the clang static analyser almost spookily perfect. It's much better to have a compiler catch an issue than put in something that will cause a runtime issue down the line. For instance, initialising a pointer to NULL will suppress the compiler warning but it won't stop the core dump when you try to dereference it.
However, if you are using a modern compiler, you are probably using C99 which means you don't need to declare the variable until you know a sensible value for it. So that's what I would do.

Initializing the variables is always useful and is a good coding practice.
This could be understand with this example:
an uninitialized variable will contain some garbage value in it. And if you didn't initialize it and by mistake you tried to use it. You could get some unpredicted results.
For example:
int test(void)
{
int a; //uninitialized variable
//You didn't initialize a
if(a > 10)
{
//Unpredicted result
}
else{}
return 0;
}
The situation becomes severe in case of bigger programs, where these types of miss are common.
So to avoid silly errors which might otherwise could consume lot of time in debugging them, variables should always be initialized

Related

Is there anyway to know if a variable has been initialized in C?

I'm currently working on a program which picks up input(via main) and draws different fractals depending on the input.
I'm saving the parsed and converted(to a number)user input, in a structure:
typedef struct
{
unsigned int xcord,ycord;
}point_t;
typedef struct
{
int fractalType;
double lstart,lend,lconstant;
double leftangle,rightangle;
point_t drawStart;
}input_data_t;
The problem I'm having is that certain fractals don't use all the variables contained in the structure, and if a certain fractal is called with a variables it doesn't use I must show an error.
Anyways now on to the problem, I know that variables when DECLARED "pick up " garbage from what was before hand in the assigned memory position. Is there any way to know if a variable has been initialized during run time, as to insure after parsing that no unnecessary variable has been used? (If so I need a cross platform solution)
No, there is no way to find this out directly. Reading from an uninitialized variable invokes undefined behavior and there is no way to recover from that. However, you have a few options to prevent this from happening.
If your variables have meaningful default values, just initialize them to those defaults before doing anything else with them. You still won't be able to tell the difference between a variable that was defaulted and one that just happens to have the same value but if your logic works without that knowledge, then this is perfectly fine. (For example, if you were to plot a sine function f(x) = a + b sin(c x + d), it would be natural to default a and d to 0 and b and c to 1.)
If your parameters don't span the entire value range of the data type, you could initialize them to some sentinel value and check for that before using them. For example, you could use NAN for floating-point values or −1 for quantities of any type that cannot be negative. Many people dislike this solution because it is all too easy to forget checking the value and using the sentinel as if it were a proper value, thus computing garbage. I believe that there is a time and place for every technique but this one is probably indeed overused.
If everything else fails, you can add a flag per variable that indicates whether it has a value. To make this usable, I recommend you create a data type with a reasonable name such as this one.
struct optional_float
{
bool initialized; // always safe to read, set appropriately
float value; // only safe to read if initialized == true
};
In C++, you can do much better by using the new std::experimental::optional<T>. But I realize that the C++ tag was removed from your question.
Finally, be sure to run your code through a debugger such as Valgrind or use a sanitizer to detect accidental reads from uninitialized variables.
I don't think there is method to check a variable wether initialiez or not .
As default variable in c has a random value or 0 before you initialize it.
If you want to know wether a variable is initialzed ,you can make a legal value scope of this variable. Before you use it ,you can check wether the value is inside the scope.
The best method in c to safty using variables is checking it by yourself if you are to use it.
why not just initialize that struct with some invalid value, then the problem become whether the value is invalid.

Coding standards: variable initialization

Some coding standards mandate initializing each variable when you declare it, even if the value is meaningless and the variable will soon be over written.
For example:
main()
{
char rx_char;
:
:
rx_char = get_char();
}
My co-worker asks me to initialize rx_char, but I don't understand why. Could anybody point out the reason?
"Initializing each variable when you declare it, even if the value is meaningless" is a schoolbook example of a cargo cult behavior. It is a completely meaningless requirement, which should be avoided whenever possible. In many cases a meaningless initializer is not much better than a random uninitialized value. In cases when it can actually "save the day", it does so by sweeping the problem under the carpet, i.e. by hiding it. Hidden problems are always the worst. When the code has a problem in it, it is always better to have it manifest itself as quickly as possible, even through having the code to crash or behave erratically.
Additionally, such requirements can impede compiler optimizations by spamming the compiler with misleading information about the effective value lifetime associated with the variable. The optimizer can treat an uninitialized variable as non-existent, thus saving valuable resources (e.g. CPU registers). In order to acquire the same kind of knowledge about a variable initialized with a meaningless value, the optimizer has to be able to figure out that it is indeed meaningless, which is generally a more complicated task.
The same problem has to be solved by a person reading the code, which impedes readability. A person unfamiliar with the code cannot say right away whether the specific initializer is meaningful (i.e. the code below relies on the initial value) or meaningless (i.e. provided thoughtlessly by a follower of the aforementioned cargo cult).
It is worth noting also that some modern compilers can detect attempts to use uninitialized variable values at both compile-time and run-time. Such compilers issue compile-time warnings or run-time assertions (in debugging builds) when such attempt is detected. In my experience this feature is much more useful than it might appear at first sight. Meanwhile, thoughtless initialization of variables with meaningless values effectively defeats this compiler-provided safety feature and, again, hides the associated errors. It certainly does more harm than good from that point of view.
Fortunately, the problem is no longer as acute as it used to be. In the modern versions of the C language variables can be declared anywhere in the code, which significantly reduces the harmful effects of such coding standards. You no longer have to declare variables at the beginning of the block, which greatly increases the chances that by the time you are ready to declare the variable you are also ready to supply a meaningful initializer for it.
Initializers are good. But when you see that you cannot provide a meaningful initializer for a variable, it is always a better idea to attempt to reorganize the code in order to create an opportunity for a meaningful initializer, instead of giving up and just using a meaningless one. This is often possible even in pre-C99 code.
With modern compilers often giving a warning about the use of uninitialised variables I'd favour not initialising towards some bogus value. Then, if someone accidentally uses the variable before the initialisation you'll get a warning, rather than having to spend X time debugging and finding out the error.
It's good practice to initialize your variables, even if it's just to set them to the types "null" equivalent. If someone else comes along and wants to edit that code, and uses rx_char before you've initialized it, they will get non-deterministic behavior. The value of rx_char would be dependent on things outside of your control. Some compilers 0 initialize variables, but you should not depend on this!
By initializing it on declaration, you're guaranteeing deterministic behavior. Which is in general, easier to debug, than having rx_char be something completely random, as it could potentially be, if you left it uninitialized.
main() {
char rx_char;
//Some stuff
char your_coworkers_char = rx_char;
//Some other stuff
rx_char = get_char();
putchar(your_cowowarers_char); //Potentially prints randomness!
}
This is perhaps optimal, unless you're working with super old style compilers you should be fine with this.
main() {
//some stuff
char rx_char = get_char();
putchar(your_cowowarers_char); //Potentially prints randomness!
}
Anybody could point out the reason?
The first person you should ask is the co-worker that asked you to do it. Her reasons may be entirely different than what we come up with.
...
Most coding standards are as much about the future as they are about what happens today.
Today, yes, it doesn't make any difference if you have char rx_char or char rx_char = 0. But in the future, what happens if someone deletes the rx_char=getchar() line? Then rx_char is a random, uninitialized value. If rx_char is 0 then you'll still have a bug, but it won't be random.

global variable initialization optimization

Global variables are initialized to "0" by default.
How much difference does it make (if any) when I explicitly assign value "0" to it.
Is any one of them faster/better/more optimized?
I tried with a small sample .c program but I do not see any change in executable size.
Edit:0 I just want to understand the behavior. Its not a bottleneck for me in any way.
The answer to your question is very implementation specific but typically all uninitialized global and static variables end up in the .bss segment. Explicitly initialized variables are located in some other data segment. Both of these will be copied over by the program loader before the execution of main(). So, there shouldn't be any performance difference between explicitly initializing to zero, and leaving the variable uninitialized.
IMO it is good practice to explicitly initialize globals and statics to zero, as it makes it clear that a zero initial value is expected.
When you say optimized, I am assuming you mean faster in execution. If so, then there won't be any difference. And the compiler might even remove the initialization of the global variable (not sure on the compiler internals). And if you mean the space utilization of the program - there won't be a difference in that either.
Bigger question though is - is there a specific reason you are trying to look to optimize via the initialization of global variables. Can you please explain a bit more.
Static objects without an explicit initializer are initialized to zero at startup. Whether you explicitly initialize the object to 0 or not will probably make no difference in term of performance as the compiler usually initialize all the zero objects in one go before main.
// File scope
// Same code is likely to be generated for the two objects initialization
int bla1;
int bla2 = 0;
On the other hand, if you assign 0 instead of initializing, it could make a difference because the compiler could not infer what was the previous value of the object.
void init(void)
{
bla1 = 0;
bla2 = 0;
}
I doubt there is a difference, but, even if there is, I have much more doubts about the fact that your program is so optimized that the bottleneck is that.
I'd rather suggest not to care at all about all this kind of issues and write the code as you like, maybe giving way to readability rather than speed, leaving optimization only as a final problem.
Premature optimization is the root of all evil
There is none. The optimizer sees that as a no-op.
Explicit initialization is more verbose and clearer to the untrained eye. If you have juniors in your team, I'd explicitly initialize these variables.

Why we must initialize a variable before using it? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What happens to a declared, uninitialized variable in C? Does it have a value?
Now I'm reading Teach Yourself C in 21 Days. In chapter 3, there is a note like this:
DON'T use a variable that hasn't been initialized. Results can be
unpredictable.
Please explain to me why this is the case. The book provide no further clarification about it.
Because, unless the variable has static storage space, it's initial value is indeterminate. You cannot rely on it being anything as the standard does not define it. Even statically allocated variables should be initialized though. Just initialize your variables and avoid a potential headache in the future. There is no good reason to not initialize a variable, plenty of good reasons to do the opposite.
On a side note, don't trust any book that claims to teach you X programming language in 21 days. They are lying, get yourself a decent book.
When a variable is declared, it will point to a piece of memory.
Accessing the value of the variable will give you the contents of that piece of memory.
However until the variable is initialised, that piece of memory could contain anything. This is why using it is unpredictable.
Other languages may assist you in this area by initialising variables automatically when you assign them, but as a C programmer you are working with a fairly low-level language that makes no assumptions about what you want to do with your program. You as the programmer must explicitly tell the program to do everything.
This means initialising variables, but it also means a lot more besides. For example, in C you need to be very careful that you de-allocate any resources that you allocate once you're finished with them. Other languages will automatically clean up after you when the program finished; but in C if you forget, you'll just end up with memory leaks.
C will let you get do a lot of things that would be difficult or impossible in other languages. But this power also means that you have to take responsibility for the housekeeping tasks that you take for granted in those other languages.
You might end up using a variable declared outside the scope of your current method.
Consider the following
int count = 0;
while(count < 500)
{
doFunction();
count ++;
}
...
void doFunction() {
count = sizeof(someString);
print(count);
}
In C, using the values of uninitialized automatic variables (non-static locals and parameter variables) that satisfy the requirement for being a register variable is undefined behavior, because such variables values may have been fetched from a register and certain platforms may abort your program if you read such uninitialized values. This includes variables of type unsigned char (this was added to a later C spec, to accommodate these platforms).
Using values of uninitialized automatic variables that do not satisfy the requirement for being a register variable, like variables that have their addresses taken, is fine as long as the C implementation you use hasn't got trap representations for the variable type you use. For example if the variable type is unsigned char, the Standard requires all platforms not to have trap representations stored in such variables, and a read of an indeterminate value from it will always succeed and is not undefined behavior. Types like int or short don't have such guarantees, so your program may crash, depending on the C implementation you use.
Variables of static storage duration are always initialized if you don't do it explicitly, so you don't have to worry here.
For variables of allocated storage duration (malloc ...), the same applies as for automatic variables that don't satisfy the requirements for being a register variable, because in these cases the affected C implementations need to make your program read from memory, and won't run into the problems in which register reads may raise exceptions.
In C the value of an uninitialized variable is indeterminate. This means you don't know its value and it can differ depending on platform and compiler. The same is also true for compounds such as struct and union types.
Why? Sometimes you don't need to initialize a variable as you are going to pass it to a function that fills it and that doesn't care about what is in the variable. You don't want the overhead of initialization imposed upon you.
How? Primitive types can be initialized from literals or function return values.
int i = 0;
int j = foo();
Structures can be zero intialized with the aggregate intializer syntax:
struct Foo { int i; int j; }
struct Foo f = {0};
At the risk of being pedantic, the statement
DON'T use a variable that hasn't been initialized.
is incorrect. If would be better expressed:
Do not use the value of an uninitialised variable.
The language distinguishes between initialisation and assignment, so the first warning is, in that sense over cautious - you need not provide an initialiser for every variable, but you should have either assigned or initialised a variable with a useful and meaningful value before you perform any operations that subsequently use its value.
So the following is fine:
int i ; // uninitialised variable
i = some_function() ; // variable is "used" in left of assignment expression.
some_other_function( i ) ; // value of variable is used
even though when some_function() is called i is uninitialised. If you are assigning a variable, you are definitely "using" it (to store the return value in this case); the fact that it is not initialised is irrelevant because you are not using its value.
Now if you adhere to
Do not use the value of an uninitialised variable.
as I have suggested, the reason for this requirement becomes obvious - why would you take the value of a variable without knowing that it contained something meaningful? A valid question might then be "why does C not initialise auto variables with a known value. And possible answers to that would be:
Any arbitrary compiler supplied value need not be meaningful in the context of the application - or worse, it may have a meaning that is contrary to the actual state of the application.
C was deliberately designed to have no hidden overhead due to its roots as systems programming language - initialisation is only performed when explicitly coded, because it required additional machine instructions and CPU cycles to perform.
Note that static variables are always initialised to zero. .NET languages, such as C# have the concept of an null value, or a variable that contains nothing, and that can be explicitly tested and even assigned. A variable in C cannot contain nothing, but what it contains can be indeterminate, and therefore code that uses its value will behave non-deterministically.

Why variables start out with random values in C

I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?
The variables start out uninitialized because that's the fastest way - why waste the CPU cycles on initialization if you're going to write another value there anyway?
If you want a variable to be initialized after creation, just initialize it. :)
About it being a dangerous thing: Every good compiler will warn you if you try to use a variable without initialization.
No. C is a very efficient language, one that has traditionally been faster that a lot of other languages. One of the reasons for this is that it doesn't do too much on it's own. The programmer controls this.
In the case of initialization, C variables are not initialized to a random value. Rather, they are not initialized and so they contain whatever was at the memory location before.
If you wanted to initialize a variable to, say, 1 in your program, then it would be inefficient if the variable had already been initialized to zero or null. That would mean it was initialized twice.
Execution speed and overhead (or lack thereof) are the main reasons why. C is notorious for letting you walk off the proverbial cliff because it always assumes that the user knows better than it does.
Note that if you declared the variable as static it actually is guaranteed to be initialized to 0.
Variables start out with a random value because you are just handed a block of memory and told to deal with it yourself. It has whatever value that block of memory had before hand. Why should the program waste time setting the value to some arbitrary default when you are likely going to set it yourself later?
The design choice is performance, and it is one of the many reasons why C isn't the preferred language for most projects.
This has nothing to do with "if C were being designed today" or with efficiency of one initialization. Instead think of something like
void foo()
{
struct bar *ptrs[10000];
/* do something where only a few indices end up actually getting used */
}
Any language that forces useless initialization on you is doomed to be slow as hell for algorithms that can make use of sparse arrays where you don't care about the majority of the values, and have an easy way of knowing which values you care about.
If you don't like my example with such a large object on the stack, substitute malloc instead. It has the same semantics with regard to initialization.
In either case, if you want zero-initialization, you can get it with {0} or calloc.
It was a design choice made many ears ago, probably for efficiency reasons.
Statically allocated variables (globals and statics) are initialized to 0 if there's no explicit initialization - this could be justified even taking efficiency into account becuase it only occurs once. I'd guess the thinking was that for automatic variables (locals) that are allocated each time a scope is entered, implicit initialization was considered something that might cost too much and therefore should be left to the programmer's responsibility.
If C were being designed today, I wouldn't be surprised if that design decision were changed - especially since compilers are intelligent enough today to be able to optimize away an initialization that gets overwritten before any other use (or potential use).
However, there are so many C compiler toolchains that follow the spec of not initializing automatically, it would be foolish for a compiler to perform implicit initialization to a 'useful' value (like 0 or NULL). That would just encourage people targeting that tool chain to write code that didn't work correctly on other tool chains.
However, compilers can initialize local variables, and they often do. It's just that they initialize the locals to a values that's not generally useful (especially, that doesn't set a pointer to the null pointer). That kind of initialization isn't useful in writing your programming logic against, and it's not intended for that. It's intended to cause deterministic and reproducible errors so that if you erroneously use values that have been set by implicit initialization, you'll be able to find it easily in test/debug.
Usually this compiler behavior is turned on only for debug builds; I could see an argument being made for turning it on in release builds as well - particular if the release build can still optimize it away when the compiler can prove that the implicit initialized value is never used.

Resources