CWE-122: Heap-based buffer overflow | Causes and Fixes Skip to content

Security weaknessCWE Top 25 · #16

CWE-122 Heap-based buffer overflow

A program writes past a dynamically allocated memory block, corrupting nearby data and risking crashes or code execution.

  • Senior security engineers
  • 540+ projects delivered
  • Reply within one business day

Quick answer

What is CWE-122?

Heap-based Buffer Overflow: The product writes past the end of a buffer that was allocated on the heap.

Business impact

What CWE-122 could cost your business

MITRE documents what this weakness can do. Here is what that means for a website, store or app.

Confidentiality

Private data exposed

Customer records, credentials, orders or internal files can be read by people who should never see them.

  • Execute Unauthorized Code or Commands
  • Bypass Protection Mechanism
  • Modify Memory

Integrity

Data, pages or code changed

Prices, orders, content or the code your site runs can be altered without your approval.

  • Execute Unauthorized Code or Commands
  • Bypass Protection Mechanism
  • Modify Memory

Availability

Downtime and lost sales

Crashes, slowdowns or exhausted resources can take your site, store or app offline.

  • DoS: Crash, Exit, or Restart
  • DoS: Resource Consumption (CPU)
  • DoS: Resource Consumption (Memory)

Access Control

Accounts and admin areas exposed

Logins and permission checks can be bypassed, putting admin and customer accounts at risk.

  • Execute Unauthorized Code or Commands
  • Bypass Protection Mechanism
  • Modify Memory

In plain English

What Heap-based buffer overflow means for your business

  • 540+projects delivered
  • 9+years in business
  • 23+certified experts
Get a free security check

A senior engineer replies within one business day.

The heap is the pool of memory a program requests while it runs, for data whose size is not known in advance, such as an uploaded image or an incoming message. A heap-based buffer overflow happens when code writes more into one of those blocks than was requested for it. The extra bytes overwrite whatever the memory manager placed next: other data, internal bookkeeping, or pointers to functions the program will call.

These bugs often start with a size miscalculation. The program reads a length from a file or message, allocates too little, then copies too much. That is why file and network parsers written in C and C++ are frequent locations. For a business running a website, the practical exposure is through media libraries, server software, native app code and device firmware. A crafted file can crash the service or, in the worst case, run an attacker’s code.

Where it shows up

  • Image, video, audio and font libraries that allocate memory based on dimensions or lengths declared inside a file your site processes.
  • Compression and archive tools, and PDF or office document converters, that run on your server when customers upload files.
  • Native mobile apps and embedded web view components that decode media or parse network data in C or C++.
  • Embedded and IoT firmware, and outdated server software such as web servers, proxies and databases that your site depends on.

Free security check

Is CWE-122 hiding in your site?

A senior engineer checks your site, store or app for this weakness and the rest of the CWE Top 25, then sends a prioritized fix plan within one business day. No obligation.

Official definition

How MITRE defines CWE-122

Heap-based Buffer Overflow

The product writes past the end of a buffer that was allocated on the heap.

Also known as: Heap Overflow, Heap Buffer Overflow

Weakness ID
CWE-122
Type
Variant
Status
Draft
Likelihood of exploit
High
Applies to
Memory-Unsafe, C, C++
Introduced during
Implementation
2025 CWE Top 25
Rank 16

Fix it

How to fix Heap-based buffer overflow

Practical steps in priority order. Share them with your developer or agency.

  1. Patch libraries and server software

    Update media libraries, converters, runtimes and the operating system as soon as security fixes are released. Rebuild container images and app bundles so they include the patched versions, not just the host.

  2. Validate sizes before allocating and copying

    Check every length, width, height and count taken from input against sane limits. Guard size arithmetic against integer overflow. Before each copy, confirm the amount written cannot exceed the size that was actually allocated.

  3. Use safer languages and containers

    Use a language or compiler that performs automatic bounds checking, such as Rust, Go, Java or C#. In C++, use std::vector, std::string and checked access instead of raw allocation and pointer arithmetic.

  4. Sandbox file processing

    Run image, video and document conversion in an isolated worker with low privileges, no secrets, limited memory and no network access. A corrupted heap in that worker then cannot reach your main application or database.

  5. Harden and test native builds

    Enable hardened allocators, address space layout randomization and non-executable memory. Fuzz every parser with AddressSanitizer turned on, and add static analysis to continuous integration. These are defense in depth, not a complete solution.

Signs you may be affected

  • A media or document conversion service crashes on particular files and needs restarting.
  • Scans flag heap overflow or memory corruption advisories in libraries bundled with your app or server.
  • Native code computes allocation sizes from input values without checking for overflow or mismatch.

Questions to ask your developer

  • Which libraries process uploaded images, videos and documents on our server?
  • Are those conversions isolated from the main application and its credentials?
  • When a library is patched, do we rebuild our containers and app releases?

Prevention

What MITRE recommends, phase by phase

Every mitigation from the CWE entry, in the order a project runs: plan, build, test, operate.

  1. 01

    Architecture and Design

    • Use an abstraction library to abstract away risky APIs. Not a complete solution.
  2. 02

    Implementation

    • Pre-design: Use a language or compiler that performs automatic bounds checking.
    • Implement and perform bounds checking on input.
    • Do not use dangerous functions such as gets. Look for their safe equivalent, which checks for the boundary.
  3. 03

    Build and Compilation

    • Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking. D3-SFCV (Stack Frame Canary Validation) from D3FEND.
    • Run or compile the software using features or extensions that randomly arrange the positions of a program’s executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code. Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables.
  4. 04

    Operation

    • Use OS-level preventative functionality. This is not a complete solution, but it provides some defense in depth.

Detection and evidence

How CWE-122 is found, and where it has hit

The testing methods MITRE recommends, and real vulnerabilities this weakness has caused.

How it is detected

  • FuzzingFuzz testing (fuzzing) is a powerful technique for generating large numbers of diverse inputs – either randomly or algorithmically – and dynamically invoking the code with those inputs. Even with random inputs, it is often capable of generating unexpected results such as crashes, memory corruption.
  • Automated Dynamic AnalysisUse tools that are integrated during compilation to insert runtime error-checking mechanisms related to memory safety errors, such as AddressSanitizer (ASan) for C/C++ [REF-1518].

Real vulnerabilities it caused

  • CVE-2025-46687Chain: Javascript engine code does not perform a length check (CWE-1284) leading to integer overflow (CWE-190) causing allocation of smaller buffer than expected (CWE-131) resulting in a heap-based buffer overflow.
  • CVE-2021-43537Chain: in a web browser, an unsigned 64-bit integer is forcibly cast to a 32-bit integer (CWE-681) and potentially leading to an integer overflow (CWE-190). If an integer overflow occurs, this can cause heap memory.
  • CVE-2007-4268Chain: integer signedness error (CWE-195) passes signed comparison, leading to heap overflow (CWE-122)
  • CVE-2009-2523Chain: product does not handle when an input string is not NULL terminated (CWE-170), leading to buffer over-read (CWE-125) or heap-based buffer overflow (CWE-122).
  • CVE-2021-29529Chain: machine-learning product can have a heap-based buffer overflow (CWE-122) when some integer-oriented bounds are calculated by using ceiling() and floor() on floating point values (CWE-1339)
  • CVE-2010-1866Chain: integer overflow (CWE-190) causes a negative signed value, which later bypasses a maximum-only check (CWE-839), leading to heap-based buffer overflow (CWE-122).

How we fix it

From finding to fixed: how Codefreex closes CWE-122

  1. Scan and confirm

    We test your site, store or app for this weakness and the rest of the CWE Top 25 with automated scanning and manual review, and confirm what is actually exploitable.

  2. Fix at the source

    We change the code, configuration or dependency that causes it, not just the symptom, and plan the changes to avoid downtime.

  3. Verify the fix

    We retest every finding, check that nothing else broke and hand you a short report you can share with your team, client or auditor.

  4. Keep it fixed

    Updates, monitoring and maintenance so the weakness does not return with the next plugin, theme, app or code change.

FAQ

CWE-122: FAQs

Short answers for owners and developers. Not sure whether your site is affected? Ask us to check.

How does a heap overflow reach a normal website?

Usually through a file or request handled by native code. Your site may be written in PHP or JavaScript, but when it resizes an image or converts a document it calls a library written in C or C++. If that library has a heap overflow, a crafted upload can trigger it. Keeping those libraries current closes the gap.

How severe is a heap-based buffer overflow?

Severity is high. The common result is a crash and lost availability. In more serious cases an attacker can overwrite data or function pointers on the heap and run their own code, which can bypass other security controls. MITRE rates the likelihood of exploitation as high. Sandboxing limits how far the damage spreads.

How do I prevent heap overflows?

For code you write, validate all sizes, guard against integer overflow, and prefer bounds-checked languages and containers. Test parsers with fuzzing and memory sanitizers. For code you only use, apply security updates quickly, rebuild anything that bundles the library, and process untrusted files in an isolated, low-privilege environment.

What is CWE-122?

CWE-122, “Heap-based Buffer Overflow”, is a software weakness catalogued by MITRE in the Common Weakness Enumeration. The product writes past the end of a buffer that was allocated on the heap.

How serious is CWE-122?

MITRE rates the likelihood of exploit as High. It can affect availability, integrity, confidentiality, access control, with impacts such as dos: crash, exit, or restart, dos: resource consumption (cpu), dos: resource consumption (memory). It ranks number 16 on the 2025 CWE Top 25 Most Dangerous Software Weaknesses. The real risk depends on where the weakness sits and what data or functions it exposes.

How do you prevent CWE-122?

Pre-design: Use a language or compiler that performs automatic bounds checking. Use an abstraction library to abstract away risky APIs. Not a complete solution.

Can Codefreex check my site for CWE-122?

Yes. A senior engineer reviews your site, store or app for CWE-122 and the rest of the CWE Top 25, confirms what is exploitable and sends a prioritized fix plan within one business day. Start with the free security check form on this page.

Free security check

Find out if CWE-122 affects your site

Send your URL. A senior engineer checks for this weakness and the rest of the CWE Top 25, and replies within one business day with what to fix first.

  • A senior strategist reviews your request, not a sales bot
  • Clear scope, timeline and estimate within one business day
  • Free 30-minute discovery call, no obligation
  • NDA available on request

Weakness data from the Common Weakness Enumeration (CWE®) version 5.0, Copyright © 2006–2026, The MITRE Corporation. CWE is free to use by any organization or individual for any research, development, and/or commercial purposes under the CWE Terms of Use. CWE is a registered trademark of The MITRE Corporation. The business impact, risk profile and plain-English guidance on this page are written by Codefreex and are general information, not a security assessment of your system.