Unable to locate the Bug
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 th开发者_Python百科is 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?
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.
i think the new code is better. Except I would have gone
char data_string[] = "data data data";
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.
精彩评论