Journal Articles

CVu Journal Vol 32, #3 - July 2020 + Programming Topics
Browse in : All > Journals > CVu > 323 (11)
All > Topics > Programming (877)
Any of these categories - All of these categories

Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.

Title: Static Analysis in GCC and Clang

Author: Bob Schmidt

Date: 05 July 2020 17:27:42 +01:00 or Sun, 05 July 2020 17:27:42 +01:00

Summary: Silas S. Brown shares some experiences of analysing code.

Body: 

Did you know that GCC version 10 (available in Debian 10, Fedora 32, etc) has a flag called -fanalyzer that turns on static analysis?

Clang has had a ‘Clang Static Analyzer’ since at least 2011, although this is not always included in the default Clang distribution (in GNU/Linux it’s usually packaged separately under ‘clang-tools’ or ‘clang-analyzer’). It can be run with the command scan-build make as long as your Makefile uses $(CC) and $(CXX) to compile C and C++ with the default compiler.

Static analysis can be likened to having extra-paranoid warnings. It can ‘false positive’ and warn about things that are not in fact problems. I was incorrectly warned by GCC 10.1.1 that Listing 1 leaks memory (it didn’t seem to realise the static global was kept for later), and Clang gave me a ‘use after free’ warning on a branch that gives a pointer to realloc() but uses the original pointer if realloc() returned NULL (Clang’s analyser seemed to think realloc() could both return NULL and also free the pointer, which is not according to the standard). Clang also warned me about null pointer dereferencing because it hadn’t realised a function I’d called would, in the event of null pointer, return a false value that would stop the code from going down the branch that uses the pointer. (That function was in another module, so the analyser couldn’t check it and had to assume it might return true when given null.) But the output of a static analyser can still be worth checking and thinking about: it found a couple of unused assignments in my code for example, and one place where there could be a division by zero given invalid user input.

  #include <stdlib.h>
  typedef struct { int a; } S;
  static S *sList;
  static int sLen;
  int alloc_sList(int n) {
    sList = calloc(n,sizeof(S));
    if(!sList) n = 0;
    sLen = n;
    return n;
  }

Silas S. Brown Silas is a partially-sighted Computer Science post-doc in Cambridge who currently works in part-time assistant tuition and part-time for Oracle. He has been an ACCU member since 1994.

Notes: 

More fields may be available via dynamicdata ..