Receber por email
← Voltar para o catálogo

static-bug-detector

Analyze source code statically to detect potential functional bugs including null dereferences, incorrect condition checks, unreachable code, inconsistent state updates, logic errors, resource leaks, and type mismatches. Report suspicious code locations with detailed explanations, severity levels, and confidence assessments. Use when reviewing code for bugs, performing code audits, or when the use

105estrelas
Atualizado há 8 meses

Ver no GitHub ↗ Licença: Apache-2.0

Como adicionar

/plugin marketplace add ArabelaTso/Skills-4-SE

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/static-bug-detector/svg)](https://www.skillteca.com.br/skills/static-bug-detector)
#ai

Skills relacionadas

Ver todas de DevOps e Infra →

Alerta por categoria

Receba novas skills de DevOps e Infra toda segunda

1 email curto, só com as skills novas de DevOps e Infra. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

Static Bug Detector

Overview

Perform static analysis on source code to identify potential functional bugs. Detect common bug patterns, analyze control flow and data flow, and report suspicious locations with explanations, severity levels, and confidence assessments.

Bug Detection Workflow

Step 1: Understand the Code

Analyze the code structure and semantics:

  1. Identify language:
  2. Determine programming language
  3. Understand language-specific semantics
  4. Note language idioms and conventions
  1. Parse code structure:
  2. Functions/methods
  3. Classes/types
  4. Control flow (if, loops, etc.)
  5. Data flow (assignments, returns)
  1. Build context:
  2. Variable declarations and types
  3. Function signatures
  4. Class hierarchies
  5. Dependencies
  1. Identify scope:
  2. What code to analyze
  3. Entry points
  4. Critical paths

Step 2: Detect Bug Patterns

Scan for common bug patterns:

  1. Null dereference bugs:
  2. Variables from nullable sources
  3. Dereferences without null checks
  4. Null checks after use
  5. Undocumented null returns
  1. Incorrect conditions:
  2. Always true/false conditions
  3. Assignment in condition (= vs ==)
  4. Redundant conditions
  5. Inverted logic
  6. Wrong operators
  1. Unreachable code:
  2. Code after return/throw
  3. Always-false branches
  4. Dead code paths
  1. Inconsistent state:
  2. Partial state updates
  3. Updates without validation
  4. Non-atomic operations
  5. Broken invariants
  1. Logic errors:
  2. Off-by-one errors
  3. Wrong operator precedence
  4. Infinite loops
  5. Incorrect boolean logic
  1. Resource issues:
  2. Resource leaks
  3. Double free/close
  4. Use after free/close
  1. Type issues:
  2. Type mismatches
  3. Implicit coercion
  4. Invalid casts

Step 3: Analyze Severity

Assess the impact of each bug:

High Severity:

  • Causes crashes or exceptions
  • Data corruption
  • Security vulnerabilities
  • Guaranteed runtime errors

Medium Severity:

  • Incorrect behavior
  • Potential errors (context-dependent)
  • Performance issues
  • Maintainability problems

Low Severity:

  • Code smells
  • Redundant code
  • Minor inefficiencies
  • Style issues that might hide bugs

Step 4: Assess Confidence

Determine confidence in the bug report:

High Confidence (90-100%):

  • Clear violation of language semantics
  • Guaranteed to cause error
  • Well-known bug pattern
  • No ambiguity

Medium Confidence (60-89%):

  • Likely bug but context-dependent
  • May be intentional in rare cases
  • Suspicious pattern
  • Needs verification

Low Confidence (30-59%):

  • Unusual but possibly valid
  • Could be intentional design
  • Needs more context
  • Style issue that might hide bug

Factors:

  • Code context available
  • Language semantics clarity
  • Pattern recognition
  • Documentation consistency

Step 5: Generate Report

Produce structured bug report:

  1. For each bug:
  2. Bug type/category
  3. Location (file, line, range)
  4. Severity level
  5. Confidence level
  6. Description
  7. Why it's a bug
  8. Potential impact
  9. Recommendation/fix
  1. Organize by:
  2. Severity (high first)
  3. Confidence (high first)
  4. Location (file order)
  5. Bug type (grouped)
  1. Include:
  2. Code context
  3. Example fixes
  4. Related bugs
  5. Summary statistics

Bug Categories

For detailed patterns and examples, see [detection_patterns.md](references/detection_patterns.md).

Quick Reference

| Bug Category | Common Patterns | Severity | Detection Difficulty | |--------------|----------------|----------|---------------------| | Null Dereference | No null check, null after use | High | Easy | | Incorrect Conditions | = vs ==, always true/false | High-Medium | Easy | | Unreachable Code | After return, dead branch | Low | Easy | | Inconsistent State | Partial update, no validation | High-Medium | Medium | | Logic Errors | Off-by-one, wrong precedence | High-Medium | Medium | | Resource Issues | Leaks, double close | Medium | Medium | | Type Issues | Mismatch, implicit coercion | Medium-Low | Easy |

Examples

Example 1: Null Dereference

Input Code (Java):

public String getUserName(int userId) {
    User user = userRepository.findById(userId);
    return user.getName();
}

Analysis Output:

## Bug: Potential null dereference

**Location:** line 3
**Severity:** High
**Confidence:** High (95%)

### Description
Variable 'user' may be null but is dereferenced without null check.

### Why This Is a Bug
Method 'findById' may return null if user not found. Calling 'getName()'
on null will throw NullPointerException.

### Potential Impact
- Runtime NullPointerException
- Application crash
- Poor user experience

### Recommendation
Add null check before dereferencing:

public String getUserName(int userId) { User user = userRepository.findById(userId); if (user == null) { return null; // or throw exception } return user.getName(); }


Or use Optional:

public Optional<String> getUserName(int userId) { return Optional.ofNullable(userRepository.findById(userId)) .map(User::getName); }

Example 2: Incorrect Condition

Input Code (C):

int status = getStatus();
if (status = SUCCESS) {
    printf("Operation successful\n");
}

Analysis Output:

## Bug: Assignment in condition

**Location:** line 2
**Severity:** High
**Confidence:** High (98%)

### Description
Using assignment operator '=' instead of comparison operator '==' in condition.

### Why This Is a Bug
Expression 'status = SUCCESS' assigns SUCCESS to status and evaluates to
SUCCESS value. This is almost always a typo for 'status == SUCCESS'.

### Potential Impact
- Condition always evaluates to true (if SUCCESS is non-zero)
- Original status value lost
- Logic error in program flow

### Recommendation
Change to comparison operator:

if (status == SUCCESS) { printf("Operation successful\n"); }


Most compilers warn about this. Enable warnings: -Wall -Wextra

Example 3: Off-by-One Error

Input Code (Python):

def process_array(arr):
    for i in range(len(arr) + 1):
        print(arr[i])

Analysis Output:

## Bug: Off-by-one error (array index out of bounds)

**Location:** line 2-3
**Severity:** High
**Confidence:** High (100%)

### Description
Loop iterates one past the end of array, causing IndexError.

### Why This Is a Bug
range(len(arr) + 1) produces indices 0 to len(arr) inclusive. Array
indices are 0 to len(arr)-1, so arr[len(arr)] is out of bounds.

### Potential Impact
- IndexError exception
- Program crash
- Incorrect behavior

### Recommendation
Remove the +1:

def process_array(arr): for i in range(len(arr)): print(arr[i])


Or use idiomatic iteration:

def process_array(arr): for item in arr: print(item)

Example 4: Resource Leak

Input Code (Python):

def read_config(path):
    f = open(path)
    config = json.load(f)
    return config

Analysis Output:

## Bug: Resource leak

**Location:** line 2
**Severity:** Medium
**Confidence:** High (90%)

### Description
File opened but never closed, causing resource leak.

### Why This Is a Bug
File handle opened on line 2 is never closed. If exception occurs during
json.load or in normal execution, file remains open.

### Potential Impact
- File descriptor leak
- Resource exhaustion with many calls
- File locking issues on Windows

### Recommendation
Use context manager to ensure cleanup:

def read_config(path): with open(path) as f: config = json.load(f) return config


Or ensure close in finally:

def read_config(path): f = open(path) try: config = json.load(f) return config finally: f.close()

Example 5: Inconsistent State Update

**Input

Compartilhar X LinkedIn