Why uninitialized variables are bad (Linux kernel and more)

I've always been an avid hater of uninitialized variables. I'll hunt them down, catch them and beat them to a bloody pulp and then shoot the remains.

Too much, you say? No need for the bat AND the gun, you say? Oh, quite the contrary.

Here is an example of a recently discovered Linux kernel issue. An uninitialized memory segment. The fix is really simple: to initialize it with zeros. This was done in a patch that only adds the following command:

+ memset(mem, 0, sizeof(mem));

Oh, but I can hear you snicker behind your monitor "this won't happen in Perl because Perl protects you from such stuff!"

You're right, this won't happen in Perl. But here's a Perl example:

At $work I've written a program that runs checks on servers (rest assured, it's not a Nagios replacement) and creates an array of the results of each server that was tested. The array contains timing and whenever there's a timeout, it contains an "undef" to indicate a penalty.

Every once in a while (this is an event-based program so there's another POE::Session that does this) there's a checker that takes the history, replaces the penalties with the numerical penalty value, gets the average and decides whether to act upon the information. Once it decides to act upon it, it runs another event which actually does the work.

With me so far? Okay.

When checking the logs of the test machine running this service, I've noticed some uninitialized warnings (since I "use warnings" all the time) and after taking a closer look at them, I noticed that one of the wokers fails to update the history with the penalty value. This can be fixed in a single line but it actually brought up an issue that a certain diff operation failed (Perl resolving the undef to 0 instead of 500!) and creating the opposite reaction.

You can say "well, you should have tested, then!" and that's what I would say too, only I already have a rather large testing suite for it and it failed to find this bug. You don't always find your bugs (even with 100% coverage) and if you've listened to Ovid in the past year or two, you already know that.

Uninitialized variables are bad, warnings are good. Those are my 2 bytes.


Hi Sawyer

If you'd used strict and warnings in your blog post, you would have noticed that you had an undefined, undeclared global variable in your text: $work.

What kind of example does this set?

Clint :P

In the older versions of Apache with mod_perl, it used to re-use the memory without reinitializing it. That means whatever was used in the previous run was used again this the next. This has been corrected but it goes to show that even relying on perl to initialize your variables is not a guarantee. You should get ito the habit of always initializing your variables.

Leave a comment

About Sawyer X

user-pic Gots to do the bloggingz