Home > Articles > Programming > C/C++

  • Print
  • + Share This

Code Inspection

If you follow the rules of resource management strictly, you'll never have problems with resource leaks or double deletions. You'll also reduce the chances of accessing stray pointers. Then again, you won't have these problems if you just follow the traditional rules of always deleting the pointers allocated using new, never deleting them twice, and so on. So what's the big deal?

There is one big difference between the two approaches. It's orders of magnitude easier to find the violations of the rules of resource management than it is to find traditional resource bugs. The idea is that the former can be found by simple code inspection or in a single test run, whereas the latter are hidden in rarely executed parts of code and show up only under heavy stress.

Imagine that you were to code-review a piece of traditional software for possible memory leaks. First thing, of course, would be to grep for all occurrences of new. For each call to new, you'd have to find out what happens to the pointer to which the result of the allocation was assigned. You'd have to make sure that all possible execution paths lead to the eventual deletion of this pointer. You'd have to check for break statements, returns from the middle of a procedure, and exceptions. The original pointer may be assigned to another pointer, so you'd follow that pointer, too.

Contrast it with the review of a piece of code written according to the rules of resource management. Just as in the previous case, you'd grep for new. But this time, you'd only have to inspect the closest vicinity of the call:

  • Is this a direct transfer to a strong pointer, or are we inside a constructor of an object?

  • Is the result of the call immediately stored within the object, with no exception-prone code following it in the constructor?

  • If so, is there a corresponding delete in the destructor of the object?

Next, you'd grep for all the occurrences of release and perform the same checks.

The difference is between having to review and understand every single path of execution versus making just a few localized tests. Doesn't it remind you of the difference between unstructured and structured programming? In principle, you could convince yourself of the correctness of a program with gotos. You'd just have to follow all possible branches. In a structured program, on the other hand, you can localize your inspection to structural blocks of code. Locality is the key in both cases.

Failure modes in resource management are also easier to debug. The most common bug is trying to access a strong pointer after it releases the ownership of the resource. This causes an immediate fault and is extremely easy to track.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.