Detecting Buggy Code with Machine Learning: What I Learned Building a Real Defect Detection System
Software bugs cost the industry an estimated $2 trillion a year. Every shipped defect is a potential security vulnerability, a failed deployment, or a frustrated user. For my Machine Learning final project, I wanted to tackle this from first principles: can we train a model to look at raw C/C++ source code and predict whether it contains a defect — before it ever runs?
The short answer is yes, but it's harder than it sounds. Here's what I built, what worked, and what didn't.
The Problem
Automated defect detection is a binary classification task. Given a function written in C or C++, label it 1 (defective) or 0 (clean). The challenge is that "defectiveness" isn't a surface-level pattern — it's a semantic property of logic, memory management, and control flow. A function can look perfectly readable and still have an off-by-one error buried in a loop condition.
The Dataset
I used the CodeXGLUE Defect Detection benchmark — 27,318 real-world C/C++ functions extracted from the FFmpeg and QEMU open-source projects, labeled using the project's CVE (security vulnerability) history.
| Split | Functions |
|---|---|
| Train | 21,854 |
| Validation | 2,732 |
| Test | 2,732 |
| Total | 27,318 |
The class balance was 54% defective / 46% clean — close enough that I didn't need class weighting. This is a real-world dataset, not a toy benchmark. The defects span buffer overflows, null pointer dereferences, resource leaks, and integer errors.
Figure 1 — Distribution of function lengths (whitespace tokens). Most functions are short (20–100 tokens), but the tail extends to 1000+. This heavily right-skewed distribution informed our tokenization and truncation strategy.
Three Approaches, Increasing Complexity
I structured the project as a progressive comparison: start simple, add complexity, see what each step buys you.
Baseline 1: TF-IDF + Logistic Regression
Accuracy: 0.607The simplest possible approach: treat source code like a bag of words. I tokenized each function using unigram and bigram features (top 20,000 by TF-IDF weight), then trained an L2-regularized logistic regression classifier.
Surprisingly competitive for how little it knows about code structure. TF-IDF picks up surface-level patterns — functions that frequently use malloc, free, or pointer arithmetic lean defective. But it has no understanding of order, scope, or control flow. It's essentially a vocabulary fingerprint.
Figure 2 — Confusion matrix for Baseline 1 (TF-IDF + Logistic Regression). TP=638, FP=456, FN=617, TN=1021. The model struggles with recall — missing 617 of 1255 actual defects (49%).
Baseline 2: Code Metrics + XGBoost
Accuracy: 0.557Instead of raw text, I hand-engineered structural features: lines of code, number of loops (for, while), conditionals, pointer dereference counts, and function call counts. I fed these into an XGBoost gradient boosted tree.
This was the worst performer — which was surprising. My hypothesis going in was that structural metrics would capture meaningful signal. What I learned: the features I extracted were too coarse. A function being "long" doesn't make it defective. The bugs lived in the semantics, not the structure. Better features (cyclomatic complexity, data flow depth, call graph position) might have helped here.
Figure 3 — Confusion matrix for Baseline 2 (Code Metrics + XGBoost). TP=419, FP=374, FN=836, TN=1103. Worst recall of all three models — misses 66% of actual defects.
Main Model: Fine-Tuned CodeBERT
Accuracy: 0.651microsoft/codebert-base is a transformer pre-trained on both natural language and source code (Python, Java, JavaScript, PHP, Ruby, Go, C). It understands that -> is a pointer dereference, that if introduces a branch, and that identifiers have semantic relationships.
I fine-tuned it on the training split for 5 epochs using AdamW with mixed precision (fp16) on a GPU runtime. A classification head was added on top of the [CLS] token representation.
This was the best result — confirming the hypothesis: semantic pre-training on programming languages meaningfully outperforms lexical and structural approaches.
Figure 4 — Confusion matrix for CodeBERT Fine-Tuned. TP=591, FP=290, FN=664, TN=1187. Best precision (0.671) and accuracy, but still misses 53% of defects — the recall problem persists.
Results Summary
| Model | Accuracy | Defect Recall | Defect Precision |
|---|---|---|---|
| TF-IDF + Logistic Regression | 0.607 | 0.508 | 0.583 |
| Code Metrics + XGBoost | 0.557 | 0.334 | 0.528 |
| CodeBERT Fine-Tuned | 0.651 | 0.471 | 0.671 |
The Critical Limitation: Recall
Accuracy alone is a misleading metric for defect detection. What actually matters is: when there's a real defect, does the model catch it?
CodeBERT's defect recall was only 0.47 — it missed more than half of actual defects.
Explainability: What Is the Model Actually Looking At?
After training, I used SHAP (SHapley Additive exPlanations) to probe which tokens most influenced the model's predictions. I generated explanations for both vulnerable and clean function samples.
Figure 5 — SHAP for vulnerable functions. Tokens like user, buffer, and increment patterns push toward defect prediction.
Figure 6 — SHAP for safe functions. Include patterns and standard string operations push toward clean prediction.
The results were instructive — and humbling. On vulnerable functions, the model weighted buffer, char, strcpy, and len heavily. On safe functions, return, NULL, and bound-checking patterns dominated.
Key Takeaways
What worked
- Pre-trained code models (CodeBERT) substantially outperform from-scratch baselines on semantic tasks
- The dataset is large enough that fine-tuning converges reliably within 5 epochs
- SHAP gives meaningful post-hoc explanations even for transformer models
What didn't
- Hand-crafted structural metrics underperformed because the feature set was too shallow
- High accuracy masked poor defect recall — always report both metrics for safety-critical tasks
- SHAP revealed the model relies on vocabulary patterns, not program semantics
What I'd do next
- Graph-based code representations (Abstract Syntax Trees, Program Dependency Graphs) to give the model actual structural knowledge
- Defect-type-specific fine-tuning — buffer overflows and null dereferences are different problems that likely need different models
- Larger, more diverse datasets beyond FFmpeg/QEMU
- Recall-optimized training — using class-weighted loss or precision/recall-targeted thresholds