Featured Webinar: Simplify Compliance Workflows With New C/C++test 2024.2 & AI-Driven Automation Watch Now

What Is Static Code Analysis?
A Comprehensive Overview

Jump to Section

Overview

Innovative static code analysis tools drive continuous quality for software development. Compliance automation with a range of coding standards delivers high-quality, safe, and secure coding for enterprise and embedded software development.

What Is Static Code Analysis?

Static analysis is the process of analyzing source code for the purpose of finding bugs and evaluating code quality without the need to execute it. Developers and testers run static analysis on partially complete code, libraries, and third-party source code.

Static code analyzers use a compiler-like front-end to build a syntactic and semantic model of the software. The syntactic model is then analyzed against a set of rules or “checkers” to see if the code is in violation. These checkers use pattern-matching algorithms to detect errors including:

  • Poor use of language constructs
  • Use of insecure functions
  • Violations of coding guidelines

Static analysis is highly recommended or required by some companies building applications to safety standards like ISO 26262, DO-178C, IEC 62304, IEC 61508, and EN 50716. It helps organizations detect hard-to-find defects and improve software safety, security, and reliability by conforming to coding standards such as MISRA, AUTOSAR C++ 14, CERT, CWE, OWASP, and others.

“MISRA”, “MISRA C” and the triangle logo are registered trademarks of The MISRA Consortium Limited. ©The MISRA Consortium Limited, 2021. All rights reserved.

How Does Static Code Analysis Work?

Static code analyzers use a compiler-like front end to build a syntactic and semantic model of the software. The syntactic model is then analyzed against a set of rules or “checkers” to see if the code is in violation.

Blue circle with a white icon of a word bubble with a blue exclamation point in the middle.

Define Rules

The checkers use pattern-matching algorithms to detect errors like poor use of language constructs, use of insecure functions, and violations of coding guidelines. The specific set of checkers used is configurable by the user. Some static analysis tools provide pre-set configurations for convenience, for instance, for coding standards such as MISRA C 2023.

Blue circle with a white control settings icon.

Use Data & Control Flow

More sophisticated checkers employ semantic analysis that uses data and control flow to detect complex bugs and security vulnerabilities. To do this, the static analyzer builds an execution model of the software, considers possible paths through the code, and evaluates use of data as it flows from source (like user input) to its destination (such as an API call or system call).

Blue circle with an icon showing three white stacked lines getting incrementally shorter with the longest on top and shortest line on the bottom.

Apply Heuristics

Analyzing every single possible condition and path would be too time consuming, so the analyzer uses heuristics to detect the most likely paths for evaluation. Types of errors detected by these checkers include null pointer deference, buffer overflows, and security vulnerabilities like command and SQL injections.

A graphic showing the static analysis process as source code moves from the source repository to static analyzer, then violations get reported to the Parasoft team server.
A high level view of the static analysis process

Ways to Apply Static Analysis

Teams most often use static analysis in two ways:

  1. At the developer desktop integrated into their development environment (IDE).
  2. At the command line as part of a build or continuous integration process.

Some commercial tools integrate with leading IDEs and provide solutions for users to effectively manage analysis results. In fact, artificial intelligence and machine learning can also be applied in the prioritization and management of all identified violations to reduce effort and risk.

Comparing Static Analysis vs. Dynamic Analysis

 

Image of a table comparing static analysis and dynamic analysis benefits.

 

Combining static and dynamic analysis is the best option for getting actionable results, reducing bug occurrences, increasing bug detection, and creating more secure code overall. One is not better or worse than the other. They work in tandem like all the gears of a perfectly crafted Swiss watch.

 

The SDLC pipeline and what stages static analysis and dynamic analysis find defects.
The SDLC pipeline and what stages static analysis and dynamic analysis find defects.

Static Code Analysis Techniques

Static analysis is the process of examining source without the need for execution for the purposes of finding bugs or evaluating code quality. This means that teams can run static analysis on partially complete code, libraries, and third-party source code. In the application security domain, static analysis goes by the term static application security testing (SAST).

Pattern-Based Static Analysis

Looks for code patterns that violate defined coding rules. In addition to ensuring that code meets uniform expectations for regulatory compliance or internal initiatives, it also helps teams prevent defects like resource leaks, performance and security issues, logical errors, and API misuse.

Flow-Based Static Analysis

Involves finding and analyzing the various paths that can be taken through the code both by control (the order in which lines can be executed) and by data (the sequences in which a variable or similar entity can be created, changed, used and destroyed). This can expose problems that lead to critical defects such as memory corruptions (buffer overwrites), memory access violations, null pointer dereferences, race conditions or deadlocks. It can also detect security issues by pointing out paths that bypass security-critical code, for example, code that performs authentication or encryption.

Complexity Analysis

Involves measuring and visualizing various aspects of the code. It can help detect existing defects, but more often it warns of potential difficulty in preventing and detecting future defects when code is maintained. This is done by finding complexity and unwieldiness such as:

  • Overly large components
  • Excessive nesting of loops
  • Too lengthy series of decisions
  • Convoluted intercomponent dependencies

Code Duplication Analysis

Checking for duplicate code helps organizations improve application design and decrease maintenance costs. During this type of analysis, code is parsed into smaller language elements (tokens). The tokens are analyzed according to a set of rules that specify what should be considered duplicate code. There are two types of rules:

  • Simple rules find single token duplicates like string literals.
  • Complex rules find multiple token duplicates like duplicate methods or statements.

Considerations When Looking for a Tool

When selecting a static code analysis tool for safety and security-critical applications, there are key factors to consider.

Icon inside a blue circle showing a white outline of a guideline checklist.

Certified by a TÜV Certification Authority

For safety and security-critical applications, a solution that’s been certified by a TÜV certification authority such as TÜV SÜD for use on safety-critical systems for monitoring static analysis coding standards like MISRA and AUTOSAR C++ 14.

Icon inside a blue circle showing a white outline of a guideline checklist.

Provides a Compliance Summary Report

A compliance summary report that documents the state of compliance for each guideline and any other associated deviations or recategorization.

Icon inside a blue circle showing a white outline of a guideline checklist.

Supports Industry Coding Standards

Supports 2500+ different rules that cover industry coding standards such as AUTOSAR C++ 14, MISRA, JSF, CERT, CWE, and more.

What Are the Benefits of a Static Code Analysis Tool?

Blue circle showing a white, upward trending arrow in the center.

Increase Code Quality & Reduce the Cost of Defects

Prevent code defects early in any development process before they turn into more expensive challenges in the later stages of software testing.

Icon of security shield.

Satisfy Industry Functional Standards

Usher in static analysis solutions that are recommended by process standards such as ISO 26262, DO-178C, IEC 62304, IEC 61508, EN 50716 or EN 50128, and more.

Icon of a padlock

Satisfy Static Analysis Security Testing (SAST)

Weave compliance with security coding standards like SEI CERT, CWE, OWASP, DISA-ASD-STIG, and UL 2900 into the SA testing processes and to be certain that your code meets stringent security standards.

Blue circle showing an icon of a white-outlined magnifying glass zooming in on open and closed white carets.

Satisfy Safety Coding Compliance Standards

Establish compliance with safety coding standards such as MISRA, AUTOSAR C++ 14, JSF, and more, or create your own custom coding standards configuration for your organization.

Blue circle with a white icon showing two squares connected by a curved line.

Easily integrate static analysis into your streamlined CI/CD pipeline with continuous testing that quickly delivers high-quality software.

Icon inside a blue circle showing a white 4-pronged connector with AI written in the center.

Test Smarter With AI & ML

Incorporate artificial intelligence and machine learning to improve productivity in your team’s static analysis workflow. The AI will flag and prioritize the most urgent violations that need to be fixed first.

What Are the Possible Limitations of a Static Code Analysis Tool?

  • Generates False Positives and Negatives
    SAST tools often generate false positives and false negatives. False positives flag non-issues, wasting developers’ time, while false negatives miss real vulnerabilities, posing security risks. Balancing the reduction of false positives without increasing false negatives is challenging.
  • Complexities of Static Analysis and Software Systems
    Static code analysis is challenging for SAST tools due to the need for deep understanding of code structure, logic, and data flow without execution. As software complexity increases, SAST tools may miss security issues or generate false positives. They also struggle with dynamic, data-driven web applications where user inputs and interactions vary.
  • Identifying Vulnerabilities From Unsanitized Inputs
    SAST tools often miss vulnerabilities from unsanitized inputs, like SQL injection or XSS, because they rely on static code analysis. They struggle to detect issues arising from improperly validated and sanitized external inputs.
  • Dependency on Specific Programming Languages
    SAST tools are often language-specific, excelling in some languages but struggling with others. Organizations using multiple languages may need several SAST tools or one that supports their entire tech stack, posing a logistical challenge.

Tips to Perform Static Code Analysis With Success

One of the best things you can do to be successful is to understand the four main types of static code analysis and the errors these tests are designed to detect.

Icon of a lightbulb

Performance Tests

Performance tests identify errors that will address overall performance issues and help developers keep up with the latest best practices.

Icon of a lightbulb

Security-Related Source Code Analysis

Security-related source code analysis finds security risks like weak cryptography, configuration problems, and framework-specific command injection errors.

Icon of a lightbulb

Safety and Reliability Tests

Safety and reliability tests help prevent issues with functionality because no one wants off-hour emergency unresponsive service messages. This type of static code analysis is especially useful for finding memory leaks or threading problems.

Icon of a lightbulb

Style Tests

Style tests encourage teams to adopt uniform coding styles for ease of use, understanding, and bug fixing. Developers don’t have to waste time identifying style violations. The tests find them, which saves time.

Best Practices to Perform Static Code Analysis With Success

Maximize the effectiveness of static code analysis to improve code quality, reduce defects, and meet compliance requirements efficiently by following these best practices.

  1. Incorporate static code analysis early in the development cycle, ideally from the beginning of coding.
  2. Automate static analysis by integrating it into the continuous integration/continuous deployment (CI/CD) pipeline.
  3. Encourage developers to fix issues in real time and make code quality part of their daily workflow.
  4. Focus on incremental analysis by examining only the code changes rather than analyzing the entire codebase each time.
  5. Tailor static analysis rules to match the coding standards relevant to your project or industry, such as MISRA for automotive or CERT for security-critical systems. Enforce these rules as part of the development process.
  6. Focus on fixing the most critical and high-severity issues first. Use triage to categorize findings into levels of importance: security vulnerabilities, code correctness, performance, and style violations.
  7. Utilize dynamic dashboards and reporting tools to track key metrics like the number of issues fixed, compliance levels, and code quality trends over time.
  8. Keep the static analysis tool updated with the latest rules, bug-fixing patterns, and compliance checks.
  9. Use static analysis in combination with other testing methods, such as unit testing and code coverage, to create a robust quality assurance process.

Getting Started: How Is Static Analysis Performed?

Static analysis tools can be effective when a project is incomplete and partially coded. That means these tools can be introduced and used at any phase of a software development project, which is a major benefit in software engineering. It’s important to consider the maturity of the product under development because it can impact the way static analysis can be adopted.

The biggest challenge with introducing static analysis is that a compilation of a large amount of code can produce a large number of warnings.

That’s why your focus should be on getting your team as productive as possible when integrating static analysis into a project. This will prevent your team from being overwhelmed by the many static analysis warnings they will most likely have. Most developers don’t have the luxury of immediately fixing existing or legacy code.

As your team becomes more proficient, you will be able to incorporate secondary goals such as improving overall quality and enforcing the organization’s coding standards. Developers can analyze results quickly, deal with false positives, and fix bugs efficiently as static analysis becomes a daily routine. They will also be able to deal with false positives.

Below are some approaches for getting started with static analysis at different development states.

Icon of a target or bullseye

Existing Project in the Market

The primary approach to adopting static analysis for these projects is called acknowledge-and-defer. Because there isn’t a lot of new code being developed, all of the discovered bugs and security vulnerabilities are added to the existing technical debt.

Icon of a circle half filled with blue and half white to indicate project in progress, halfway complete.

Existing Project With Current Development

The recommended approach to integration is called a line-in-the-sand approach. This approach means improving new code as it’s developed while deferring less critical warnings as technical debt.

Blue circle with two concentric circles inside it thinly outlined in white.

New Project

Developers can integrate static analysis in their development environments from the very start and in a control flow manner to ensure code is written at a high-quality standard. The approach to adoption, in this case, is aptly named greenfield.

Exploring Real-Life Applications of Static Code Analysis

The key to successfully running static analysis is an easy-to-use, accessible tool that gives developers useful, actionable information upfront without overwhelming them.

Rectangular banner image with primarily dark blue and angled corner in standard blue. In upper right corner is a collage of Parasoft product icons for DTP, C/C++test, CTP, Jtest, Selenic, Insure++, C/C++test CT, dotTEST, Virtualize, and SOAtest.

Elevate your software testing with Parasoft solutions.