Sunday, January 06, 2008

Top Ten, 12 of 10

When we last left our hero, we were looking at ten ways to get screwed by the "C" programming language. Today's entry is Uninitialized local variables.

Once again, gcc's -Wall option warns with: 'B' may be used uninitialized in this function, even for the more complicated version. The only way that this is a problem is that sometimes you have a case where a variable is always set, but possibly in different places. The compiler doesn't know that at least one path will be taken, so it thinks a variable might not be initialized, and warn you. In these cases, i usually break down and provide a redundant initialization. At least it's cheap.

Initialization of a variable is probably cheap, especially if it's infrequent. So, the optimization of leaving it off, because you know it won't be used before set probably doesn't save much memory or time. Now that compilers can warn you of this condition, they could also optimize out an explicit initialization, and do it safely. Of course, if you initialize a variable with the return value of a function, the compiler would also have to compute any side effects before it could optimize it away.

3 comments:

Anonymous said...

11 of 12 and 12 of 12? Does that leave implicit the sort of errors related to buffer overflow and the like?

Anonymous said...

I *mean* 11 of 10 and 12 of 10, of course.

Stephen said...

The original "top ten" post has more than ten entries. I posted my articles one day at a time, and apparently didn't notice right away. I really should have started the series with "1 of 10". But since the C language numbers array entries starting with zero, i really would have wanted, perhaps an introduction article, part "0 of 10".

I have a series of boxes of Christmas ornaments in my basement. They're labeled "1 of 7", "2 of 7", and so on up to "12 of 7". Well, there used to be seven boxen.

I see that the original referenced article now has 20 entries. Time to add a couple articles, i think.