Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Using the Clang Static Analyzer


In this recipe, you will learn about the static analysis of code, which is carried out by the Clang Static Analyzer. It is built on top of Clang and LLVM. The static analysis engine used by the Clang Static Analyzer is a Clang library, and it has the capability to be reused in different contexts by different clients.

We will take the example of the divide-by-zero defect and show you how the Clang Static Analyzer handles this defect.

Getting ready

You need to build and install LLVM along with Clang.

How to do it…

Perform the following steps:

  1. Create a test file and write the test code in it:

    $ cat sa.c
    int func() {
    int a = 0;
    int b = 1/a;
    return b;
    }
    
  2. Run the Clang Static Analyzer by passing the command-line options shown in the following command, and get the output on the screen:

    $ clang -cc1 -analyze -analyzer-checker=core.DivideZero sa.c
    sa.c:3:10: warning: Division by zero
    int b = 1/a;
            ~^~
    1 warning generated.
    

How it works…

The static analyzer core performs...