Skip to content

CWE-131: Incorrect Calculation of Buffer Size

cwe.mitre.org September 8, 2026

DoS: Crash, Exit, or Restart; Execute Unauthorized Code or Commands; Read Memory; Modify Memory

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.

Strategy: Input Validation

Architecture and Design

Effectiveness: Moderate

Architecture and Design

Strategy: 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

Strategy: 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.

Effectiveness: 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

Strategy: 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 ].

Effectiveness: Defense in Depth

Strategy: 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 ].

Effectiveness: Defense in Depth

Strategy: Compilation or Build Hardening

Architecture and Design; Operation

Strategy: Environment Hardening

Architecture and Design; Operation

Strategy: 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.

Effectiveness: Limited

Class: Memory-Unsafe (Undetermined Prevalence)

C (Undetermined Prevalence)

C++ (Undetermined Prevalence)

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.

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.

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.

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.

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().

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.

Note: this is a curated list of examples for users to understand the variety of ways in which this weakness can be introduced. It is not a complete list of all CVEs that are related to this CWE entry.

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.

Automated Dynamic Analysis

Effectiveness: Moderate

Automated Dynamic Analysis

Effectiveness: Moderate

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.

Automated Static Analysis - Binary or Bytecode

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

Bytecode Weakness Analysis - including disassembler + source code weakness analysis

Binary Weakness Analysis - including disassembler + source code weakness analysis

Manual Static Analysis - Binary or Bytecode

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

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

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

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

Focused Manual Spotcheck - Focused manual analysis of source

Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

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

Source code Weakness Analyzer

Context-configured Source Code Weakness Analyzer

Source Code Quality Analyzer

Architecture or Design Review

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

Formal Methods / Correct-By-Construction

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

This is a broad category. Some examples include:

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.