views:

117

answers:

4

I was recently on The Daily WTF when I came across this old post. In it the author mentions that one of the programmers changed this code:

int main (int argc, char **argv) 
{ 
  int x;
  char data_string[15];
  ...
  x = 2;
  strcpy(data_string,"data data data");
  ...
}

To this code:

int main (int argc, char **argv) 
{
  int x = 2;
  char data_string[15] = "data data data";
  ...
}

The author goes on to mention:

[the coder] changed every single variable to be initiated on the stack

For the life of me I cannot see how this change could be harmful, and I am worried that it is a lapse in my C knowledge. What is the WTF?

+3  A: 

I don't think the stack initialization was the problem. He was supposed to be looking for a hard-to-find memory leak, but he decided to do the initialization change instead on thousands of C files.

Although, as mentioned on wikipedia, "uninitialized variables [are] a frequent cause of bugs". You eliminate the potential for use of uninitialized variables if you take care of it at declaration. But doing that conversion to a few thousand files probably wasn't the most efficient way to find and solve the real problem.

Kaleb Brasee
Actually I thought it was to prevent null-pointer usage which can be just as (or depending on the environment/OS) more insidious. As well stack initialization helps with compiler optimizations making the code potentially faster. Depending on the intervening code complexity the assignment of x to 2 might not be done at allocation in the first example, where as you're all but guaranteed that to be the case in the second example/changed code.
Jason D
It happens, sometimes the you just throw up your hands and fix everything that _might_ be the problem.
John Knoeller
A: 

i think the new code is better. Except I would have gone

  char data_string[] = "data data data";
pm100
A: 

The only way this is worse is that it's possible that the older code never initialized (or used) the value in some code paths.

The other problem is this

char data_string[99] = "data data data";

Will initialize 99 characters rather than just the first 15. which makes this

char data_strings[99] = "";

a lot more expensive than this

char data_strings[99];
data_strings[0] = 0;

Of course, if the buffer really only needs to be big enough to hold "data data data", then this is better

char data_string[] = "data data data";

But that makes you wonder whether it was ever necessary to copy the string into a stack variable at all.

John Knoeller
A: 

If you do

char data_string[15] = "data data data";

The compiler has to create code to initialize that piece of data, resulting in a blowup of your executable. If you read the article, you can see that what fit in one CD, now needed two!

This is just my guess though.

Moron