BT
x Your opinion matters! Please fill in the InfoQ Survey about your reading habits!

An Errors List Underscores the Need for Static Code Analysis

by Abel Avram on Dec 14, 2012 |

Program Verification Systems, the creator of PVS-Studio, a static code analyzer for C and C++, has published a list of programming errors, some of them being found in popular open source projects such as Chromium, TortoiseSVN, Apache HTTP Server, MySQL, and others.

The list maintains over 150 types of coding errors, some of them being serious logical errors, others are performance related mistakes, while some are not so harmful.

Following are a couple of error types with code samples from real projects found in this list.

V502 - Perhaps the '?:' operator works in a different way than it was expected. The '?:' operator has a lower priority than the 'foo' operator.

MongoDB:

string sysInfo() {
  ....
  stringstream ss;
  ....
  ss << (sizeof(char *) == 8) ? " 64bit" : " 32bit";
  ....
}

A very nice sample. 0 or 1 will be printed instead of "32bit"/"64bit".

V511 - The sizeof() operator returns size of the pointer, and not of the array, in given expression.

Chromium:

uint8 salt_[LINK_SALT_LENGTH];

VisitedLinkMaster::TableBuilder::TableBuilder(
    VisitedLinkMaster* master,
    const uint8 salt[LINK_SALT_LENGTH])
    : master_(master),
      success_(true) {
  fingerprints_.reserve(4096);
  memcpy(salt_, salt, sizeof(salt));
}

The 'salt' object is simply a pointer. Value LINK_SALT_LENGTH in the square brackets indicates to the programmer that he is working with an array of LINK_SALT_LENGTH items. But it is not an array of items which is passed into the function - it is only the pointer. So, the sizeof(salt) expression will return value 4 or 8 (the size of the pointer in a 32-bit/64-bit system).

It is possible many of the errors signaled on this list as appearing in various open source projects to have been fixed by now. Since any programmer is prone to make errors, it is a good recommendation to run source code through one or several static code analyzers. Wikipedia hosts a page with many such tools for different languages.

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT