The product does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow.

Primary

Implementation

High

Integrity
Availability
Confidentiality
DoS: Crash, Exit, or Restart
Execute Unauthorized Code or Commands
Read Memory
Modify Memory
If the incorrect calculation is used in the context of memory allocation, then the software may create a buffer that is smaller or larger than expected. If the allocated buffer is smaller than expected, this could lead to an out-of-bounds read or write (CWE-119), possibly causing a crash, allowing arbitrary code execution, or exposing sensitive data.

Automated Static Analysis

This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives.
Automated static analysis generally does not account for environmental considerations when reporting potential errors in buffer calculations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report buffer overflows that originate from command line arguments in a program that is not expected to run with setuid or other special privileges.

High
Detection techniques for buffer-related errors are more mature than for most other weakness types.

Automated Dynamic Analysis
This weakness can be detected using dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.
Moderate
Without visibility into the code, black box methods may not be able to sufficiently distinguish this weakness from others, requiring follow-up manual methods to diagnose the underlying problem.

Automated Dynamic Analysis
Use 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].
Moderate
Crafted inputs are necessary to
reach the code containing the error, such as generated
by fuzzers. Also, these tools may reduce performance,
and they only report the error condition - not the
original mistake that led to the
error.

Manual Analysis
Manual analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. This becomes difficult for weaknesses that must be considered for all inputs, since the attack surface can be too large.

Manual Analysis

This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session.
Specifically, manual static analysis is useful for evaluating the correctness of allocation calculations. This can be useful for detecting overflow conditions (CWE-190) or similar weaknesses that might have serious security impacts on the program.

High
These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

Automated Static Analysis - Binary or Bytecode

According to SOAR [REF-1479], the following detection techniques may be useful:

Highly cost effective:

Bytecode Weakness Analysis - including disassembler + source code weakness analysis
Binary Weakness Analysis - including disassembler + source code weakness analysis

High

Manual Static Analysis - Binary or Bytecode

According to SOAR [REF-1479], the following detection techniques may be useful:

Cost effective for partial coverage:

Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies

SOAR Partial

Manual Static Analysis - Source Code

According to SOAR [REF-1479], the following detection techniques may be useful:

Cost effective for partial coverage:

Focused Manual Spotcheck - Focused manual analysis of source
Manual Source Code Review (not inspections)

SOAR Partial

Automated Static Analysis - Source Code

According to SOAR [REF-1479], the following detection techniques may be useful:

Highly cost effective:

Source code Weakness Analyzer
Context-configured Source Code Weakness Analyzer

Cost effective for partial coverage:

Source Code Quality Analyzer

High

Architecture or Design Review

According to SOAR [REF-1479], the following detection techniques may be useful:

Highly cost effective:

Formal Methods / Correct-By-Construction

Cost effective for partial coverage:

Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

High

Implementation
When allocating a buffer for the purpose of transforming, converting, or encoding an input, allocate enough memory to handle the largest possible encoding. For example, in a routine that converts "&" characters to "&amp;" for HTML entity encoding, the output buffer needs to be at least 5 times as large as the input buffer.

Implementation

Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.

Implementation
Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.

Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Implementation
When processing structured incoming data containing a size field followed by raw data, identify and resolve any inconsistencies between the size field and the actual size of the data (CWE-130).

Implementation
When allocating memory that uses sentinels to mark the end of a data structure - such as NUL bytes in strings - make sure you also include the sentinel in your calculation of the total amount of memory that must be allocated.

Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Moderate
This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). Additionally, this only addresses potential overflow issues. Resource consumption / exhaustion issues are still possible.

Implementation
Use sizeof() on the appropriate data type to avoid CWE-467.

Implementation
Use the appropriate type for the desired action. For example, in C/C++, only use unsigned types for values that could never be negative, such as height, width, or other numbers related to quantity. This will simplify validation and will reduce surprises related to unexpected casting.

Architecture and Design
Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences, or buffer allocation routines that automatically track buffer size.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]

Operation
Build and Compilation
Environment Hardening

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 [REF-1334] discusses canary-based detection in detail.

Defense in Depth

This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.

Operation
Build and Compilation
Environment Hardening

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 (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].

Defense in Depth
These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].

Operation
Environment Hardening

Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].

Defense in Depth
This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.

Implementation
Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system.

Architecture and Design
Operation
Environment Hardening
Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Architecture and Design
Operation
Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.
OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.
This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.
Be careful to avoid CWE-243 and other weaknesses related to jails.

Limited
The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget.

int i;unsigned int numWidgets;Widget **WidgetList;
numWidgets = GetUntrustedSizeValue();if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) {ExitError("Incorrect number of widgets requested!");}WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *));printf("WidgetList ptr=%p\n", WidgetList);for(i=0; i<numWidgets; i++) {WidgetList[i] = InitializeWidget();}WidgetList[numWidgets] = NULL;showWidgets(WidgetList);

However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.

The following image processing code allocates a table for images.

img_t table_ptr; /*struct containing img data, 10kB each*/int num_imgs;...num_imgs = get_num_imgs();table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs);...

This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119).

This example applies an encoding procedure to an input string and stores it into a buffer.

char * copy_input(char *user_supplied_string){
int i, dst_index;char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE);if ( MAX_SIZE <= strlen(user_supplied_string) ){die("user string too long, die evil hacker!");}dst_index = 0;for ( i = 0; i < strlen(user_supplied_string); i++ ){
if( '&' == user_supplied_string[i] ){dst_buf[dst_index++] = '&';dst_buf[dst_index++] = 'a';dst_buf[dst_index++] = 'm';dst_buf[dst_index++] = 'p';dst_buf[dst_index++] = ';';}else if ('<' == user_supplied_string[i] ){

/* encode to &lt; */

}else dst_buf[dst_index++] = user_supplied_string[i];
}return dst_buf;
}

The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands.

The following code is intended to read an incoming packet from a socket and extract one or more headers.

DataPacket *packet;int numHeaders;PacketHeader *headers;
sock=AcceptSocketConnection();ReadPacket(packet, sock);numHeaders =packet->headers;
if (numHeaders > 100) {ExitError("too many headers!");}headers = malloc(numHeaders * sizeof(PacketHeader);ParsePacketHeaders(packet, headers);

The code performs a check to make sure that the packet does not contain too many headers. However, numHeaders is defined as a signed int, so it could be negative. If the incoming packet specifies a value such as -3, then the malloc calculation will generate a negative number (say, -300 if each header can be a maximum of 100 bytes). When this result is provided to malloc(), it is first converted to a size_t type. This conversion then produces a large value such as 4294966996, which may cause malloc() to fail or to allocate an extremely large amount of memory (CWE-195). With the appropriate negative numbers, an attacker could trick malloc() into using a very small positive number, which then allocates a buffer that is much smaller than expected, potentially leading to a buffer overflow.

The following code attempts to save three different identification numbers into an array. The array is allocated from memory using a call to malloc().

int *id_sequence;

/* Allocate space for an array of three ids. */

id_sequence = (int*) malloc(3);if (id_sequence == NULL) exit(1);

/* Populate the id array. */

id_sequence[0] = 13579;id_sequence[1] = 24680;id_sequence[2] = 97531;

The problem with the code above is the value of the size parameter used during the malloc() call. It uses a value of '3' which by definition results in a buffer of three bytes to be created. However the intention was to create a buffer that holds three ints, and in C, each int requires 4 bytes worth of memory, so an array of 12 bytes is needed, 4 bytes for each int. Executing the above code could result in a buffer overflow as 12 bytes of data is being saved into 3 bytes worth of allocated space. The overflow would occur during the assignment of id_sequence[0] and would continue with the assignment of id_sequence[1] and id_sequence[2].
The malloc() call could have used '3*sizeof(int)' as the value for the size parameter in order to allocate the correct amount of space required to store the three ints.

CVE-2025-46687
Chain: 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 (CWE-122)
https://www.cve.org/CVERecord?id=CVE-2025-46687

CVE-2025-27363
Font rendering library does not properly
handle assigning a signed short value to an unsigned
long (CWE-195), leading to an integer wraparound
(CWE-190), causing too small of a buffer (CWE-131),
leading to an out-of-bounds write
(CWE-787).
https://www.cve.org/CVERecord?id=CVE-2025-27363

CVE-2020-17087
Chain: integer truncation (CWE-197) causes small buffer allocation (CWE-131) leading to out-of-bounds write (CWE-787) in kernel pool, as exploited in the wild per CISA KEV.
https://www.cve.org/CVERecord?id=CVE-2020-17087

CVE-2004-1363
substitution overflow: buffer overflow using environment variables that are expanded after the length check is performed
https://www.cve.org/CVERecord?id=CVE-2004-1363

CVE-2004-0747
substitution overflow: buffer overflow using expansion of environment variables
https://www.cve.org/CVERecord?id=CVE-2004-0747

CVE-2005-2103
substitution overflow: buffer overflow using a large number of substitution strings
https://www.cve.org/CVERecord?id=CVE-2005-2103

CVE-2005-3120
transformation overflow: product adds extra escape characters to incoming data, but does not account for them in the buffer length
https://www.cve.org/CVERecord?id=CVE-2005-3120

CVE-2003-0899
transformation overflow: buffer overflow when expanding ">" to "&gt;", etc.
https://www.cve.org/CVERecord?id=CVE-2003-0899

CVE-2001-0334
expansion overflow: buffer overflow using wildcards
https://www.cve.org/CVERecord?id=CVE-2001-0334

CVE-2001-0248
expansion overflow: long pathname + glob = overflow
https://www.cve.org/CVERecord?id=CVE-2001-0248

CVE-2001-0249
expansion overflow: long pathname + glob = overflow
https://www.cve.org/CVERecord?id=CVE-2001-0249

CVE-2002-0184
special characters in argument are not properly expanded
https://www.cve.org/CVERecord?id=CVE-2002-0184

CVE-2004-0434
small length value leads to heap overflow
https://www.cve.org/CVERecord?id=CVE-2004-0434

CVE-2002-1347
multiple variants
https://www.cve.org/CVERecord?id=CVE-2002-1347

CVE-2005-0490
needs closer investigation, but probably expansion-based
https://www.cve.org/CVERecord?id=CVE-2005-0490

CVE-2004-0940
needs closer investigation, but probably expansion-based
https://www.cve.org/CVERecord?id=CVE-2004-0940

CVE-2008-0599
Chain: Language interpreter calculates wrong buffer size (CWE-131) by using "size = ptr ? X : Y" instead of "size = (ptr ? X : Y)" expression.
https://www.cve.org/CVERecord?id=CVE-2008-0599

Memory Management

Memory

Other length calculation error

INT30-C
Ensure that unsigned integer operations do not wrap
Imprecise

MEM35-C
Allocate sufficient memory for an object
CWE More Abstract

Allowed
This CWE entry is at the Base level of abstraction, which is a preferred level of abstraction for mapping to the root causes of vulnerabilities.
Carefully read both the name and description to ensure that this mapping is an appropriate fit. Do not try to 'force' a mapping to a lower-level Base/Variant simply to comply with this preferred level of abstraction.

This is a broad category. Some examples include:

simple math errors,
incorrectly updating parallel counters,
not accounting for size differences when "transforming" one input to another format (e.g. URL canonicalization or other transformation that can generate a result that's larger than the original input, i.e. "expansion").

This level of detail is rarely available in public reports, so it is difficult to find good examples.

This weakness may be a composite or a chain. It also may contain layering or perspective differences.
This issue may be associated with many different types of incorrect calculations (CWE-682), although the integer overflow (CWE-190) is probably the most prevalent. This can be primary to resource consumption problems (CWE-400), including uncontrolled memory allocation (CWE-789). However, its relationship with out-of-bounds buffer access (CWE-119) must also be considered.

PLOVER
2006-07-19
Draft 3
2006-07-19

Eric Dalci
Cigital
2008-07-01
updated Potential_Mitigations, Time_of_Introduction

CWE Content Team
MITRE
2008-09-08
updated Applicable_Platforms, Maintenance_Notes, Relationships, Taxonomy_Mappings, Type

CWE Content Team
MITRE
2008-10-14
updated Relationships

CWE Content Team
MITRE
2008-11-24
updated Relationships, Taxonomy_Mappings

CWE Content Team
MITRE
2009-12-28
updated Demonstrative_Examples, Likelihood_of_Exploit, Observed_Examples, Potential_Mitigations

CWE Content Team
MITRE
2010-02-16
updated Common_Consequences, Demonstrative_Examples, Detection_Factors, Maintenance_Notes, Potential_Mitigations, Related_Attack_Patterns, Relationships

CWE Content Team
MITRE
2010-04-05
updated Detection_Factors, Potential_Mitigations, References, Related_Attack_Patterns

CWE Content Team
MITRE
2010-06-21
updated Common_Consequences, Detection_Factors, Potential_Mitigations, References

CWE Content Team
MITRE
2010-09-27
updated Potential_Mitigations

CWE Content Team
MITRE
2010-12-13
updated Potential_Mitigations

CWE Content Team
MITRE
2011-03-29
updated Maintenance_Notes

CWE Content Team
MITRE
2011-06-01
updated Common_Consequences

CWE Content Team
MITRE
2011-06-27
updated Relationships

CWE Content Team
MITRE
2011-09-13
updated Potential_Mitigations, References, Relationships, Taxonomy_Mappings

CWE Content Team
MITRE
2012-05-11
updated Demonstrative_Examples, Potential_Mitigations, References, Relationships

CWE Content Team
MITRE
2012-10-30
updated Potential_Mitigations

CWE Content Team
MITRE
2013-02-21
updated Demonstrative_Examples

CWE Content Team
MITRE
2013-07-17
updated References

CWE Content Team
MITRE
2014-02-18
updated Potential_Mitigations, References

CWE Content Team
MITRE
2014-07-30
updated Detection_Factors, Relationships

CWE Content Team
MITRE
2017-11-08
updated Likelihood_of_Exploit, References, Taxonomy_Mappings

CWE Content Team
MITRE
2018-03-27
updated References

CWE Content Team
MITRE
2019-01-03
updated Relationships

CWE Content Team
MITRE
2019-06-20
updated Relationships

CWE Content Team
MITRE
2020-02-24
updated Relationships

CWE Content Team
MITRE
2020-08-20
updated Relationships

CWE Content Team
MITRE
2020-12-10
updated Relationships

CWE Content Team
MITRE
2021-03-15
updated Demonstrative_Examples, Potential_Mitigations

CWE Content Team
MITRE
2022-06-28
updated Observed_Examples

CWE Content Team
MITRE
2022-10-13
updated References

CWE Content Team
MITRE
2023-01-31
updated Description

CWE Content Team
MITRE
2023-04-27
updated Potential_Mitigations, References, Relationships

CWE Content Team
MITRE
2023-06-29
updated Mapping_Notes

CWE Content Team
MITRE
2025-04-03
4.17
2025-04-03
updated Observed_Examples

CWE Content Team
MITRE
2025-09-09
4.18
2025-09-09
updated Affected_Resources, Detection_Factors, Functional_Areas, Potential_Mitigations, References

CWE Content Team
MITRE
2025-12-11
4.19
2025-12-11
updated Applicable_Platforms, Detection_Factors, Observed_Examples, References, Weakness_Ordinalities

Other Length Calculation Error