Should Local Variable Initialisation Be Mandatory?

前端 未结 17 2487
忘掉有多难
忘掉有多难 2021-02-14 01:26

The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still se

17条回答
  •  忘了有多久
    2021-02-14 02:10

    Let me tell you a story about a product I worked on in 1992 and later that, for the purposes of this story, we'll call Stackrobat. I was assigned a bug that caused the application to crash on the Mac, but not on Windows, oh and the bug was not reproducible reliably. It took QA the better part of a week to come up with a recipe that worked maybe 1 in 10 times.

    It was hell tracking down the root cause since the actual crash happened well after the action that did it.

    Ultimately, I tracked it down by writing a custom code profiler for the compiler. The compiler would quite happily inject calls to global prof_begin() and prof_end() functions and you were free to implement them yourselves. I wrote a profiler that took the return address from the stack, found the stack frame creation instruction, located the block on the stack that represented the locals for the function and coated them with a tasty layer of crap that would cause a bus error if any element was dereferenced.

    This caught something like a half dozen errors of pointers being used before initialization, including the bug I was looking for.

    What happened was that most of the time the stack happened to have values that were apparently benign if they were dereferenced. Other times the values would cause the app to shotgun its own heap, taking out the app sometime much later.

    I spent more than two weeks trying to find this bug.

    Lesson: initialize your locals. If someone barks performance at you, show them this comment and tell them that you'd rather spend two weeks running profiling code and fixing bottlenecks rather than having to track down bugs like this. Debugging tools and heap checkers have gotten way better since I had to do this, but quite frankly they got better to compensate for bugs from poor practices like this.

    Unless you're running on a tiny system (embedded, etc), initialization of locals should be nearly free. MOVE/LOAD instructions are very, very fast. Write the code to be solid and maintainable first. Refactor it to be performant second.

提交回复
热议问题