Common Weakness Enumeration

A Community-Developed List of Software Weakness Types

CWE/SANS Top 25 Most Dangerous Software Errors
Home > CWE List > CWE- Individual Dictionary Definition (2.10)  

CWE-193: Off-by-one Error

Weakness ID: 193
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
+ Alternate Terms

An "off-by-five" error was reported for sudo in 2002 (CVE-2002-0184), but that is more like a "length calculation" error.

+ Time of Introduction
  • Implementation
+ Applicable Platforms



+ Common Consequences

Technical Impact: DoS: crash / exit / restart; DoS: resource consumption (CPU); DoS: resource consumption (memory); DoS: instability

This weakness will generally lead to undefined behavior and therefore crashes. In the case of overflows involving loop index variables, the likelihood of infinite loops is also high.


Technical Impact: Modify memory

If the value in question is important to data (as opposed to flow), simple data corruption has occurred. Also, if the wrap around results in other conditions such as buffer overflows, further memory corruption may occur.

Access Control

Technical Impact: Execute unauthorized code or commands; Bypass protection mechanism

This weakness can sometimes trigger buffer overflows which can be used to execute arbitrary code. This is usually outside the scope of a program's implicit security policy.

+ Demonstrative Examples

Example 1

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.

(Bad Code)
Example Language:
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;

However, this code contains an off-by-one calculation error. 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 off-by-one buffer overflow when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption.

Example 2

The following C/C++ example demonstrates the Off-by-one error in the main method of a pattern matching utility that looks for a specific pattern within a specific file. The main method uses the string copy method, strncpy, to copy the command line user input file name and pattern to the Filename and Pattern character arrays respectively.

(Bad Code)
Example Language:
int main(int argc, char **argv)
char Filename[256];
char Pattern[32];

/* Validate number of parameters and ensure valid content */

/* copy filename parameter to variable, may cause off-by-one overflow */
strncpy(Filename, argv[1], sizeof(Filename));

/* copy pattern parameter to variable, may cause off-by-one overflow */
strncpy(Pattern, argv[2], sizeof(Pattern));

printf("Searching file: %s for the pattern: %s\n", Filename, Pattern);
Scan_File(Filename, Pattern);

However, the calls to strncpy use the sizeof method call for the size parameter that does not take into account that the strncpy will add a null terminator to each character array. Therefore if a user enters a filename or pattern that are the same size as (or larger than) their respective character arrays a null terminator will be added beyond the end of the buffer for the character arrays creating an off-by-one buffer overflow. In addition to creating a buffer overflow that may cause a memory address to be overwritten, if the character arrays are output to the user through the printf method the memory addresses at the overflow location may be output to the user.

To fix this problem, be sure to subtract 1 from the sizeof() call to allow room for the null byte to be added.

(Good Code)
Example Language:
/* copy filename parameter to variable, no off-by-one overflow */
strncpy(Filename, argv[2], sizeof(Filename)-1);

/* copy pattern parameter to variable, no off-by-one overflow */
strncpy(Pattern, argv[3], sizeof(Pattern)-1);

Example 3

Similarly, this example uses the strncat and snprintf functions incorrectly. The code does not account for the null character that is added by the second strncat function call, one byte beyond the end of the name buffer.

(Bad Code)
Example Language:
char lastname[20];
char firstname[20];
char name[40];
char fullname[40];

strncat(name, firstname, sizeof(name));
strncat(name, lastname, sizeof(name));
snprintf(fullname, sizeof(fullname), "%s", name);

By leaving a free byte at the end of the buffers for a null character to be added, the off-by-one weakness is avoided.

(Good Code)
Example Language:
char lastname[20];
char firstname[20];
char name[40];
char fullname[40];

strncat(name, firstname, sizeof(name)-1);
strncat(name, lastname, sizeof(name)-1);
snprintf(fullname, sizeof(fullname)-1), "%s", name);

Example 4

The Off-by-one error can also be manifested when reading characters from a character array within a for loop that has an incorrect continuation condition.

(Bad Code)
Example Language:
#define PATH_SIZE 60

char filename[PATH_SIZE];

for(i=0; i<=PATH_SIZE; i++) {

char c = getc();
if (c == 'EOF') {
filename[i] = '\0';

filename[i] = getc();

In this case, the correct continuation condition is shown below.

(Good Code)
Example Language:
for(i=0; i<PATH_SIZE; i++) {

Example 5

As another example the Off-by-one error can occur when using the sprintf library function to copy a string variable to a formatted string variable and the original string variable comes from an untrusted source. As in the following example where a local function, setFilename is used to store the value of a filename to a database but first uses sprintf to format the filename. The setFilename function includes an input parameter with the name of the file that is used as the copy source in the sprintf function. The sprintf function will copy the file name to a char array of size 20 and specifies the format of the new variable as 16 characters followed by the file extension .dat.

(Bad Code)
Example Language:
int setFilename(char *filename) {
char name[20];
sprintf(name, "%16s.dat", filename);
int success = saveFormattedFilenameToDB(name);
return success;

However this will cause an Off-by-one error if the original filename is exactly 16 characters or larger because the format of 16 characters with the file extension is exactly 20 characters and does not take into account the required null terminator that will be placed at the end of the string.

+ Observed Examples
Off-by-one error allows remote attackers to cause a denial of service and possibly execute arbitrary code via requests that do not contain newlines.
Off-by-one vulnerability in driver allows users to modify kernel memory.
Off-by-one error allows local users or remote malicious servers to gain privileges.
Off-by-one buffer overflow in function usd by server allows local users to execute arbitrary code as the server user via .htaccess files with long entries.
Off-by-one buffer overflow in version control system allows local users to execute arbitrary code.
Off-by-one error in FTP server allows a remote attacker to cause a denial of service (crash) via a long PORT command.
Off-by-one buffer overflow in FTP server allows local users to gain privileges via a 1024 byte RETR command.
Multiple buffer overflows in chat client allow remote attackers to cause a denial of service and possibly execute arbitrary code.
Multiple off-by-one vulnerabilities in product allow remote attackers to cause a denial of service and possibly execute arbitrary code.
Off-by-one buffer overflow in server allows remote attackers to cause a denial of service and possibly execute arbitrary code.
This is an interesting example that might not be an off-by-one.
An off-by-one enables a terminating null to be overwritten, which causes 2 strings to be merged and enable a format string.
Off-by-one error allows source code disclosure of files with 4 letter extensions that match an accepted 3-letter extension.
Off-by-one buffer overflow.
Off-by-one error causes an snprintf call to overwrite a critical internal variable with a null value.
Off-by-one error in function used in many products leads to a buffer overflow during pathname management, as demonstrated using multiple commands in an FTP server.
Off-by-one error allows read of sensitive memory via a malformed request.
Chain: security monitoring product has an off-by-one error that leads to unexpected length values, triggering an assertion.
+ Potential Mitigations

Phase: Implementation

When copying character arrays or using character manipulation methods, the correct size parameter must be used to account for the null terminator that needs to be added at the end of the array. Some examples of functions susceptible to this weakness in C include strcpy(), strncpy(), strcat(), strncat(), printf(), sprintf(), scanf() and sscanf().

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class682Incorrect Calculation
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory741CERT C Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory875CERT C++ Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base170Improper Null Termination
Research Concepts1000
CanPrecedeWeakness VariantWeakness Variant617Reachable Assertion
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Relationship Notes

This is not always a buffer overflow. For example, an off-by-one error could be a factor in a partial comparison, a read from the wrong memory location, an incorrect conditional, etc.

+ Research Gaps

Under-studied. It requires careful code analysis or black box testing, where inputs of excessive length might not cause an error. Off-by-ones are likely triggered by extensive fuzzing, with the attendant diagnostic problems.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVEROff-by-one Error
CERT C Secure CodingSTR31-CGuarantee that storage for strings has sufficient space for character data and the null terminator
CERT C++ Secure CodingSTR31-CPPGuarantee that storage for character arrays has sufficient space for character data and the null terminator
+ References
Halvar Flake. "Third Generation Exploits". presentation at Black Hat Europe 2001. <>.
Steve Christey. "Off-by-one errors: a brief explanation". Secprog and SC-L mailing list posts. 2004-05-05. <>.
klog. "The Frame Pointer Overwrite". Phrack Issue 55, Chapter 8. 1999-09-09. <>.
G. Hoglund and G. McGraw. "Exploiting Software: How to Break Code (The buffer overflow chapter)". Addison-Wesley. February 2004.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 5: Buffer Overruns." Page 89. McGraw-Hill. 2010.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 5, "Off-by-One Errors", Page 180.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Alternate_Terms, Common_Consequences, Relationships, Observed_Example, Relationship_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-12-28CWE Content TeamMITREInternal
updated Demonstrative_Examples, Potential_Mitigations
2010-02-16CWE Content TeamMITREInternal
updated Demonstrative_Examples
2010-12-13CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Observed_Examples, References, Relationships
2014-06-23CWE Content TeamMITREInternal
updated References
2014-07-30CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships

More information is available — Please select a different filter.
Page Last Updated: January 18, 2017