SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
   Static Code Analysis
   Survey of Tools
   Cppcheck
   Goal: Provide confidence that code is correct
    just by looking at it (without building or
    executing it).

   Helps us find easy bugs buried in thousands
    of lines of code (not something people are
    great at).
   Formal Methods

   Code Metrics

   Reviews and Inspection
   Formal Methods:
    ◦ Mathematical!
    ◦ Require a mathematical model and assertions!
    ◦ Often require modeling the system as a finite state machine
      and verifying each state and transition.
   Code Metrics
   Reviews and Inspection
   Formal Methods:
    Too difficult! Static analysis is supposed to save time.
   Code Metrics
   Reviews and Inspection
   Formal Methods:
     Too difficult! Static analysis is supposed to save time.
   Code Metrics:
• Identify areas where bugs are likely.
• Based on measures of code complexity rooted in graph
  theory (e.g. Cyclomatic complexity).
   Reviews and Inspection
   Formal Methods:
     Too difficult! Static analysis is supposed to save time.
   Code Metrics:
     Good, but doesn’t directly identify defects.
   Reviews and Inspection
   Formal Methods:
     Too difficult! Static analysis is supposed to save time.
   Code Metrics:
     Good, but doesn’t directly identify defects.
   Reviews and Inspection
• Just look at the code and try to find suspicious
  patterns.
• Basically what we do when performing code reviews.
   Formal Methods:
     Too difficult! Static analysis is supposed to save time.
   Code Metrics:
     Good, but doesn’t directly identify defects.
   Reviews and Inspection
    Works pretty well!
   Static Code Analysis
   Survey of Tools
   Cppcheck
   Three Popular Commercial Tools:

    ◦ PC-Lint

    ◦ Klocwork Insight

    ◦ Coverity Prevent

   One Free Software Tool:

    ◦ Cppcheck
   PC-Lint
    ◦   Commercial
    ◦   Works for C code
    ◦   Often reports many false positives.
    ◦   Probably the cheapest after Cppcheck (which is free)


   Klocwork Insight
   Coverity Prevent
   Cppcheck
   PC-Lint
   Klocwork Insight
    ◦ Commercial
    ◦ A spin-out of Nortel Networks
    ◦ Also includes project management and project
      visualization capabilities.

   Coverity Prevent
   Cppcheck
   PC-Lint
   Klocworks Insight
   Coverity Prevent
    ◦ Commercial
    ◦ Identified over 6000 bugs across 53 open-source
      projects.
    ◦ Developed from research at Stanford University.

   Cppcheck
   PC-Lint
   Klocworks Insight
   Coverity Prevent
   Cppcheck
    ◦   Open source
    ◦   Under active development.
    ◦   Has found > 400 bugs in open-source projects.
    ◦   Free!
   Static Code Analysis
   Survey of Tools
   Cppcheck
   Detects bugs in C and C++ source that compilers
    normally do not warn about!

   Cross-platform (Windows, Linux, etc)

   Fancy Qt-based GUI client!
    ◦ Also available in a command-line version

   Usable via plugins from various IDEs (but not VS):
    ◦ Eclipse
    ◦ Code::Blocks
    ◦ Hudson, Jenkins
   Packages maintained for FreeBSD, Debian and
    Ubuntu systems (sudo apt-get install cppcheck)




   Used to find bugs in many open-source
    projects:
    ◦ Linux Kernel: > 40 bugs found+fixed
    ◦ VLC Player: > 20 bugs found+fixed
    ◦ Others: 7-zip, curl, git, etc
   Bounds checking for array overruns
   Memory and resource leaks
   Unused private class functions
   Use of deprecated functions
   Wrong # of arguments given to printf or scanf
   Switch cases that fall through suspiciously
   Dozens of others…
Possible buffer overrun




      Memory leak: buf



Should be “delete[] buf”

      Resource leak: file
Cppcheck finds many of the issues
with that code (but not all)
Buffer overrun




Suspicious format specifier for a
pointer to a C string (but not
necessary a bug)
   Bounds checking for array overruns
   Unused private class functions
   Use of deprecated functions
   Memory and resource leaks
   Dozens of others…
Preprocessor

Source File
               Tokenizer


               Simplifier




                             Results
                    Checks
                                       Happy Developer
void foo(char* str)
{
        if (str == 0)
                 printf(str);
        else
                 printf("Whoa");
}


                         Tokenizer


                          Simplifier

void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else
{ printf ( "Whoa" ) ; } }
void foo(char* str)
{
        if (str == 0)
                 printf(str);
        else
                 printf("Whoa");
}                                              Indentation, spacing,
                                               NULL-checks and
                                               braces are normalized
                         Tokenizer             to simplify checks!

                          Simplifier

void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else
{ printf ( "Whoa" ) ; } }
void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else
     { printf ( "Whoa" ) ; } }



                                                      Results
                                   Checks

   Each check iterates over the tokens, and reports if it finds a
    suspicious pattern!
   Checks implemented as C functions or XML documents that
    describe the pattern to look for.
   Results categorized as error, warning, style, performance,
    portability, or informative.
 Cppcheck    is a free tool for finding
    bugs in C++ source code.

   It works by parsing the source
    code, splitting it into tokens and
    finding suspicious patterns in the
    tokens.
 Official project page:
  ◦ http://cppcheck.sourceforge.net/
 Official source repository:
  ◦ https://github.com/danmar/cppc
    heck
Static Code Analysis and Cppcheck

Weitere ähnliche Inhalte

Was ist angesagt?

12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
venkatapranaykumarGa
 

Was ist angesagt? (20)

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
The Joy of SciPy
The Joy of SciPyThe Joy of SciPy
The Joy of SciPy
 
function, storage class and array and strings
 function, storage class and array and strings function, storage class and array and strings
function, storage class and array and strings
 
Linux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScITLinux practicals T.Y.B.ScIT
Linux practicals T.Y.B.ScIT
 
Compiler design
Compiler designCompiler design
Compiler design
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?
 
Parse Tree
Parse TreeParse Tree
Parse Tree
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
Create & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptxCreate & Execute First Hadoop MapReduce Project in.pptx
Create & Execute First Hadoop MapReduce Project in.pptx
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objects
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
LR Parsing
LR ParsingLR Parsing
LR Parsing
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1
 
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
12-Syntax Directed Definition – Evaluation Order-09-06-2023.ppt
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
 
Three address code In Compiler Design
Three address code In Compiler DesignThree address code In Compiler Design
Three address code In Compiler Design
 

Andere mochten auch

CppCheck - Static code analysis tool
CppCheck - Static code analysis toolCppCheck - Static code analysis tool
CppCheck - Static code analysis tool
Avneet Kaur
 

Andere mochten auch (19)

An Introduction to PC-Lint
An Introduction to PC-LintAn Introduction to PC-Lint
An Introduction to PC-Lint
 
CppCheck - Static code analysis tool
CppCheck - Static code analysis toolCppCheck - Static code analysis tool
CppCheck - Static code analysis tool
 
Static Analysis and the FDA Guidance for Medical Device Software
Static Analysis and the FDA Guidance for Medical Device SoftwareStatic Analysis and the FDA Guidance for Medical Device Software
Static Analysis and the FDA Guidance for Medical Device Software
 
Static Code Analysis and AutoLint
Static Code Analysis and AutoLintStatic Code Analysis and AutoLint
Static Code Analysis and AutoLint
 
Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code Analysis
 
The Art of Writing Efficient Software
The Art of Writing Efficient SoftwareThe Art of Writing Efficient Software
The Art of Writing Efficient Software
 
Using gcov and lcov
Using gcov and lcovUsing gcov and lcov
Using gcov and lcov
 
Prepare for PHP Test Fest 2009
Prepare for PHP Test Fest 2009Prepare for PHP Test Fest 2009
Prepare for PHP Test Fest 2009
 
Александр Сомов "C++: препроцессор, компилятор, компоновщик"
Александр Сомов "C++: препроцессор, компилятор, компоновщик"Александр Сомов "C++: препроцессор, компилятор, компоновщик"
Александр Сомов "C++: препроцессор, компилятор, компоновщик"
 
Frama c
Frama cFrama c
Frama c
 
Static code analysis
Static code analysisStatic code analysis
Static code analysis
 
Automation using RobotFramework for embedded device
Automation using RobotFramework for embedded deviceAutomation using RobotFramework for embedded device
Automation using RobotFramework for embedded device
 
Sonarqube 20160509
Sonarqube 20160509Sonarqube 20160509
Sonarqube 20160509
 
Code coverage & tools
Code coverage & toolsCode coverage & tools
Code coverage & tools
 
SVN에서 GIT으로 전환하기
SVN에서 GIT으로 전환하기SVN에서 GIT으로 전환하기
SVN에서 GIT으로 전환하기
 
Splints
SplintsSplints
Splints
 
Splint and tractions
Splint and tractionsSplint and tractions
Splint and tractions
 
Top 10 static code analysis tool
Top 10 static code analysis toolTop 10 static code analysis tool
Top 10 static code analysis tool
 
Splint ppt by rupeshkumar
Splint ppt by rupeshkumarSplint ppt by rupeshkumar
Splint ppt by rupeshkumar
 

Ähnlich wie Static Code Analysis and Cppcheck

Code Analysis-run time error prediction
Code Analysis-run time error predictionCode Analysis-run time error prediction
Code Analysis-run time error prediction
NIKHIL NAWATHE
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
Olivera Milenkovic
 
Reducing Redundancies in Multi-Revision Code Analysis
Reducing Redundancies in Multi-Revision Code AnalysisReducing Redundancies in Multi-Revision Code Analysis
Reducing Redundancies in Multi-Revision Code Analysis
Sebastiano Panichella
 
Embedded c & working with avr studio
Embedded c & working with avr studioEmbedded c & working with avr studio
Embedded c & working with avr studio
Nitesh Singh
 

Ähnlich wie Static Code Analysis and Cppcheck (20)

Code Analysis-run time error prediction
Code Analysis-run time error predictionCode Analysis-run time error prediction
Code Analysis-run time error prediction
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
 
Improving code quality with Roslyn analyzers
Improving code quality with Roslyn analyzersImproving code quality with Roslyn analyzers
Improving code quality with Roslyn analyzers
 
CNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code AuditingCNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code Auditing
 
Embedded system
Embedded systemEmbedded system
Embedded system
 
Control hijacking
Control hijackingControl hijacking
Control hijacking
 
API Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj RollisonAPI Testing: The heart of functional testing" with Bj Rollison
API Testing: The heart of functional testing" with Bj Rollison
 
Using Static Binary Analysis To Find Vulnerabilities And Backdoors in Firmware
Using Static Binary Analysis To Find Vulnerabilities And Backdoors in FirmwareUsing Static Binary Analysis To Find Vulnerabilities And Backdoors in Firmware
Using Static Binary Analysis To Find Vulnerabilities And Backdoors in Firmware
 
Reducing Redundancies in Multi-Revision Code Analysis
Reducing Redundancies in Multi-Revision Code AnalysisReducing Redundancies in Multi-Revision Code Analysis
Reducing Redundancies in Multi-Revision Code Analysis
 
How to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveHow to Connect SystemVerilog with Octave
How to Connect SystemVerilog with Octave
 
Embedded c & working with avr studio
Embedded c & working with avr studioEmbedded c & working with avr studio
Embedded c & working with avr studio
 
[2011 CodeEngn Conference 05] Deok9 - DBI(Dynamic Binary Instrumentation)를 이용...
[2011 CodeEngn Conference 05] Deok9 - DBI(Dynamic Binary Instrumentation)를 이용...[2011 CodeEngn Conference 05] Deok9 - DBI(Dynamic Binary Instrumentation)를 이용...
[2011 CodeEngn Conference 05] Deok9 - DBI(Dynamic Binary Instrumentation)를 이용...
 
report
reportreport
report
 
C101 – Intro to Programming with C
C101 – Intro to Programming with CC101 – Intro to Programming with C
C101 – Intro to Programming with C
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
Week1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC BeginWeek1 Electronic System-level ESL Design and SystemC Begin
Week1 Electronic System-level ESL Design and SystemC Begin
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Static Code Analysis and Cppcheck

  • 1.
  • 2. Static Code Analysis  Survey of Tools  Cppcheck
  • 3. Goal: Provide confidence that code is correct just by looking at it (without building or executing it).  Helps us find easy bugs buried in thousands of lines of code (not something people are great at).
  • 4. Formal Methods  Code Metrics  Reviews and Inspection
  • 5. Formal Methods: ◦ Mathematical! ◦ Require a mathematical model and assertions! ◦ Often require modeling the system as a finite state machine and verifying each state and transition.  Code Metrics  Reviews and Inspection
  • 6. Formal Methods: Too difficult! Static analysis is supposed to save time.  Code Metrics  Reviews and Inspection
  • 7. Formal Methods: Too difficult! Static analysis is supposed to save time.  Code Metrics: • Identify areas where bugs are likely. • Based on measures of code complexity rooted in graph theory (e.g. Cyclomatic complexity).  Reviews and Inspection
  • 8. Formal Methods: Too difficult! Static analysis is supposed to save time.  Code Metrics: Good, but doesn’t directly identify defects.  Reviews and Inspection
  • 9. Formal Methods: Too difficult! Static analysis is supposed to save time.  Code Metrics: Good, but doesn’t directly identify defects.  Reviews and Inspection • Just look at the code and try to find suspicious patterns. • Basically what we do when performing code reviews.
  • 10. Formal Methods: Too difficult! Static analysis is supposed to save time.  Code Metrics: Good, but doesn’t directly identify defects.  Reviews and Inspection Works pretty well!
  • 11. Static Code Analysis  Survey of Tools  Cppcheck
  • 12. Three Popular Commercial Tools: ◦ PC-Lint ◦ Klocwork Insight ◦ Coverity Prevent  One Free Software Tool: ◦ Cppcheck
  • 13. PC-Lint ◦ Commercial ◦ Works for C code ◦ Often reports many false positives. ◦ Probably the cheapest after Cppcheck (which is free)  Klocwork Insight  Coverity Prevent  Cppcheck
  • 14. PC-Lint  Klocwork Insight ◦ Commercial ◦ A spin-out of Nortel Networks ◦ Also includes project management and project visualization capabilities.  Coverity Prevent  Cppcheck
  • 15. PC-Lint  Klocworks Insight  Coverity Prevent ◦ Commercial ◦ Identified over 6000 bugs across 53 open-source projects. ◦ Developed from research at Stanford University.  Cppcheck
  • 16. PC-Lint  Klocworks Insight  Coverity Prevent  Cppcheck ◦ Open source ◦ Under active development. ◦ Has found > 400 bugs in open-source projects. ◦ Free!
  • 17. Static Code Analysis  Survey of Tools  Cppcheck
  • 18. Detects bugs in C and C++ source that compilers normally do not warn about!  Cross-platform (Windows, Linux, etc)  Fancy Qt-based GUI client! ◦ Also available in a command-line version  Usable via plugins from various IDEs (but not VS): ◦ Eclipse ◦ Code::Blocks ◦ Hudson, Jenkins
  • 19. Packages maintained for FreeBSD, Debian and Ubuntu systems (sudo apt-get install cppcheck)  Used to find bugs in many open-source projects: ◦ Linux Kernel: > 40 bugs found+fixed ◦ VLC Player: > 20 bugs found+fixed ◦ Others: 7-zip, curl, git, etc
  • 20. Bounds checking for array overruns  Memory and resource leaks  Unused private class functions  Use of deprecated functions  Wrong # of arguments given to printf or scanf  Switch cases that fall through suspiciously  Dozens of others…
  • 21.
  • 22. Possible buffer overrun Memory leak: buf Should be “delete[] buf” Resource leak: file
  • 23. Cppcheck finds many of the issues with that code (but not all)
  • 24.
  • 25. Buffer overrun Suspicious format specifier for a pointer to a C string (but not necessary a bug)
  • 26. Bounds checking for array overruns  Unused private class functions  Use of deprecated functions  Memory and resource leaks  Dozens of others…
  • 27. Preprocessor Source File Tokenizer Simplifier Results Checks Happy Developer
  • 28. void foo(char* str) { if (str == 0) printf(str); else printf("Whoa"); } Tokenizer Simplifier void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else { printf ( "Whoa" ) ; } }
  • 29. void foo(char* str) { if (str == 0) printf(str); else printf("Whoa"); } Indentation, spacing, NULL-checks and braces are normalized Tokenizer to simplify checks! Simplifier void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else { printf ( "Whoa" ) ; } }
  • 30. void foo ( char * str ) { if ( ! str ) { printf ( str ) ; } else { printf ( "Whoa" ) ; } } Results Checks  Each check iterates over the tokens, and reports if it finds a suspicious pattern!  Checks implemented as C functions or XML documents that describe the pattern to look for.  Results categorized as error, warning, style, performance, portability, or informative.
  • 31.  Cppcheck is a free tool for finding bugs in C++ source code.  It works by parsing the source code, splitting it into tokens and finding suspicious patterns in the tokens.
  • 32.  Official project page: ◦ http://cppcheck.sourceforge.net/  Official source repository: ◦ https://github.com/danmar/cppc heck