Copy once, check twice

The fragment is taken from Audacity project. The error is detected by the following diagnostic: V501 There are identical sub-expressions to the left and to the right of the ‘-‘ operator.

sampleCount VoiceKey::OnBackward (....) {
  int atrend = sgn(buffer[samplesleft - 2]-
                   buffer[samplesleft - 1]);                          
  int ztrend = sgn(buffer[samplesleft - WindowSizeInt-2]-
                   buffer[samplesleft - WindowSizeInt-2]);


The “buffer[samplesleft – WindowSizeInt-2]” expression is subtracted from itself. This error appeared because of copying a code fragment (Copy-Paste): the programmer copied a code string but forgot to replace 2 with 1.

This a really banal error, but still it is a mistake. Errors like this are a harsh reality for programmers.

Когда я пошагово захожу в длинный цикл при дебаггинге

Correct code

int ztrend = sgn(buffer[samplesleft - WindowSizeInt-2]-
                 buffer[samplesleft - WindowSizeInt-1]);


Be very careful when duplicating code fragments.

It wouldn’t make sense to recommend rejecting the copy-paste method altogether. It’s too convenient, and too useful to get rid of such an editor functionality.

Instead, just be careful, and don’t hurry – forewarned is forearmed.

Remember that copying the code may cause many errors. Here, take a look at some examples of bugs detected with the V501 diagnostic. Half of these errors are caused by using Copy-Paste.

If you copy the code and then edit it – check what you’ve got!

Written by Andrey Karpov.

This error was found with PVS-Studio static analysis tool.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.