Could not find an error.

I was recently at 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 further notes:

[encoder] changed every single variable that should be run on the stack

Throughout my life, I do not see how this change can be harmful, and I worry that it is a failure in my knowledge of C. What is WTF?

+4
source share
3 answers

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

Although mentioned in wikipedia , "uninitialized variables [are] a common cause of errors." You eliminate the possibility of using uninitialized variables if you take care of this when declaring. But to do this conversion into several thousand files was probably not the most effective way to find and solve a real problem.

+3
source

I think the new code is better. I would also leave

  char data_string[] = "data data data"; 
0
source

The only way this is worse is that the old code never initialized (or used) the value in some code codes.

Another problem is

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

Will initialize 99 characters, not just the first 15. What does this

 char data_strings[99] = ""; 

much more expensive than that

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

Of course, if the buffer really needs to be large enough to hold β€œdata data data,” then it’s better

 char data_string[] = "data data data"; 

But this makes you wonder if you ever need to copy a string to the stack variable at all.

0
source

Source: https://habr.com/ru/post/1301069/


All Articles