Exploring and Evaluating Hallucinations in LLM-Powered Code Generation

Fang Liu, Yang Liu, Lin Shi, Houkun Huang, Ruifeng Wang, Zhen Yang, Li Zhang · DOI

Introduction

Large Language Models (LLMs) have fundamentally transformed the landscape of software engineering, yet they remain susceptible to "hallucinations"—the generation of code that appears syntactically correct but contradicts user requirements or logical constraints. While traditional benchmarks often focus on functional correctness (i.e., passing unit tests), this research argues that such a narrow focus overlooks significant quality issues. Code hallucinations are distinct from natural language hallucinations because they must operate within strict structural and semantic boundaries. This paper presents a formal taxonomy of these errors and evaluates strategies to mitigate them.

A Taxonomy of Code Hallucinations

Through a thematic analysis of 3,120 code samples generated by five prominent LLMs, researchers identified three primary categories of hallucinations:

  1. Requirement Conflicting: The model generates code that directly ignores or contradicts the user's prompt. This often occurs when models are "distracted" by variable names or common patterns that override specific instructions.
  2. Code Inconsistency: These are internal logic errors, such as using undefined variables, including "dead" code that can never execute, or violating the internal state of the program.
  3. Knowledge Hallucinations: These occur when the model misinterprets external facts, such as library APIs, version-specific features, or fundamental computer science concepts.
Extracted figure from page 3 of Exploring and Evaluating Hallucinations in LLM-Powered Code Generation

Methodology and Datasets

The study utilized two major benchmarks to represent diverse coding scenarios:

  • HumanEval: 164 hand-written Python problems focusing on standalone logic and mathematics.
  • CoderEval: 460 tasks (Python and Java) drawn from open-source projects, requiring repository-level context.

The researchers employed an "open coding" process to manually label 1,212 hallucinatory snippets. They distinguished hallucinations from simple "Logical Reasoning Errors," defining a hallucination as a failure to retain or process provided facts, whereas a reasoning error is a failure in the subsequent logical steps.

Key Insights

The Complexity Threshold

Analysis revealed a "Goldilocks zone" for prompt length. While very short prompts are often too ambiguous, prompts exceeding 350 tokens lead to significantly higher hallucination rates as the model struggles to track multiple constraints simultaneously.

Structural Logic Failures

Models frequently hallucinate the availability of data. For instance, when implementing recursive-style formulas in an iterative loop, a model might attempt to access a future state that has not yet been computed, leading to index errors or logical crashes.

Figure 2: An example of Code Inconsistency where the model attempts to access an index (i + 1) that has not yet been appended to the list, effectively hallucinating future state.

Key Results and Mitigation

  • Prevalence and Impact: A staggering 95.3% of identified hallucinations lead to incorrect functionality. Even when code passes tests, it often suffers from poor readability (14.27%) or low efficiency (5.20%).
  • Mitigation Strategies:
    • Retrieval-Augmented Generation (RAG): Highly effective for Knowledge Hallucinations by providing ground-truth documentation.
  • Self-Refine: Helped models catch logic errors but occasionally caused "error propagation" in smaller models.
  • Model Architecture: Advanced reasoning-focused models like DeepSeek-R1 showed the lowest hallucination frequency, suggesting that training objectives are more critical than raw parameter count.

Conclusion

Hallucinations remain a significant hurdle for AI-assisted coding. While larger models generally perform better, the study highlights that specific prompting strategies and architectural choices are essential for reliable code generation. Future work will focus on developing automated hallucination detectors and expanding the taxonomy to low-level languages like C++ and Rust.

Summary updated

BibTeX
@misc{liu2024exploring,
  author = {Fang Liu and Yang Liu and Lin Shi and Houkun Huang and Ruifeng Wang and Zhen Yang and Li Zhang},
  title = {{Exploring and Evaluating Hallucinations in LLM-Powered Code Generation}},
  year = {2024},
  eprint = {2404.00971},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2404.00971},
}
Figure