The Beehive, City Place, Gatwick, RH6 0PA, United Kingdom
+44 (0)20 801 74646

The pitfalls and salvation of copy paste programming

Using copy paste in software development is widely used and is often a great time saver. However, when mistakes are made the resulting errors can often be costly and difficult to detect. This post explores how advanced static analysis tools can be used to find potential defects.

So, what’s wrong with this piece of code?

After some examination, you may notice there is a difference in pattern for the 3 assignments within each loop (though imagine how difficult that might be to uncover if these 2 blocks were separated across routines or even files). Whereas the third assignment in the first loop assigns to an instance of itself, the equivalent assignment in the second loop assigns to something else. The snippet is based on Linux 2.6.6s arch\sparc64\prom\memory.c.

This is an example of a classic “Cut and Paste” error, where problems are created when the programmer realises some already written body of code can be reused with minimal consistent changes for the target location. In the case of the above, it was realised the copy needed to change the source from “total” to “taken”, but the final necessary change of making the assignment to itself was forgotten/overlooked. Such errors are common in codebases requiring repetition, such as drivers or UI object implementations.

They can also be hard to detect as they may not lead to a failure of state and subsequent crash when executed, such as a null pointer dereference or divide by zero, instead manifesting only as incorrect program behaviour – a tricky class of problem to find. Sometimes the compiler will catch them as syntax errors but not always. And finally they may not be errors at all, but even then, scrutinising separate bits of code to manually verify correctness is already hard enough when theres the logic of each block to consider, but keeping it all in your head whilst doing so just makes the task all the more difficult.

Using Codesonar, a static analysis tool, such problems and potential errors can now be quickly identified:

As described above, such instances are not guaranteed errors, thats ultimately for you to decide, but the clear use of colour and commentary really does make the process of deciding a lot easier.

Related Posts