Main Content

CWE Rule 788

Access of Memory Location After End of Buffer

Since R2026a

Description

Access of Memory Location After End of Buffer

Polyspace Implementation

The rule checker checks for these issues:

  • Insufficient destination buffer size

  • Tainted sign change conversion

  • Array access out of bounds

  • Pointer access out of bounds

  • Array access with tainted index

  • Pointer dereference with tainted offset

  • Invalid arguments in fread()

  • Mismatch between data length and size

  • Invalid use of standard library memory routine

  • Buffer overflow from incorrect string format specifier

  • String operations on null pointer

  • Invalid use of standard library string routine

  • Destination buffer overflow in string manipulation

  • Destination buffer underflow in string manipulation

Examples

expand all

Issue

Insufficient destination buffer size occurs when the destination buffer in a strcpy operation cannot accommodate the source buffer and a null terminator. This issue is reported if the size of the source buffer is unknown. Consider this code:

int main (int argc, char *argv[])
{
  const char *const input = ((argc && argv[0]) ? argv[0] : "");
  char str[100];
  strcpy(input, str); // Noncompliant
}
In this case, the size of the source buffer input is unknown. The size of the destination buffer str might be smaller than the value (strlen(input)+1). Polyspace® reports a violation on the strcpy operation.

Risk

Using a destination buffer of insufficient size might allow an attacker to cause a buffer overflow. In the preceding code example, if argv[0] contains 100 or more characters, the strcpy operation results in a buffer overflow.

Fix

Before calling the function strcpy(), allocate sufficient memory dynamically. For instance, use the function strlen() to determine the size of the source buffer and then allocate the destination buffer so that its size is greater than the value strlen(source) + 1.

Example — Destination Buffer Too Small

In this example, the size of the source buffer is unknown, while the size of the destination buffer is fixed at 128. The size of the destination buffer might not be sufficient to accommodate the characters from the source buffer and terminate the buffer with a null. Polyspace reports a violation of the rule.

#include <string.h>
  
int main(int argc, char *argv[]) {
  const char *const source = (argc && argv[0]) ? argv[0] : "";
  char destination[128];
  strcpy(source, destination);//Noncompliant
  
  return 0;
}
Correction — Allocate Sufficient Memory for Destination Buffer

This violation is resolved by allocating sufficient memory for the destination buffer. For instance, use the function strlen() to calculate the size of the source buffer and allocate sufficient memory for the destination buffer so that it can accommodate all characters from the source buffer and the null terminator ('\0' ).

#include <stdlib.h>
#include <string.h>
  
int main(int argc, char *argv[]) {
  const char *const source = (argc && argv[0]) ? argv[0] : "";
  char* destination = (char *)malloc(strlen(source)+ 1);
  if(destination!=NULL){
      strcpy(destination, source);//Compliant
  }else{
      /*Handle Error*/
  }
  //...
  free(destination);
  return 0;
}
Issue

Tainted sign change conversion looks for values from unsecure sources that are converted, implicitly or explicitly, from signed to unsigned values.

For example, functions that use size_t as arguments implicitly convert the argument to an unsigned integer. Some functions that implicitly convert size_t are:

bcmp
memcpy
memmove
strncmp
strncpy
calloc
malloc
memalign

Risk

If you convert a small negative number to unsigned, the result is a large positive number. The large positive number can create security vulnerabilities. For example, if you use the unsigned value in:

  • Memory size routines — causes allocating memory issues.

  • String manipulation routines — causes buffer overflow.

  • Loop boundaries — causes infinite loops.

Fix

To avoid converting unsigned negative values, check that the value being converted is within an acceptable range. For example, if the value represents a size, validate that the value is not negative and less than the maximum value size.

Example - Set Memory Value with Size Argument
#include <stdlib.h>
#include <string.h>

enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};

void bug_taintedsignchange(int size) {
    char str[SIZE128] = "";
    if (size<SIZE128) {
        memset(str, 'c', size);  //Noncompliant
    }
}

In this example, a char buffer is created and filled using memset. The size argument to memset is an input argument to the function.

The call to memset implicitly converts size to unsigned integer. If size is a large negative number, the absolute value could be too large to represent as an integer, causing a buffer overflow.

Correction — Check Value of size

One possible correction is to check if size is inside the valid range. This correction checks if size is greater than zero and less than the buffer size before calling memset.

#include <stdlib.h>
#include <string.h>

enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};

void corrected_taintedsignchange(int size) {
    char str[SIZE128] = "";
    if (size>0 && size<SIZE128) {
        memset(str, 'c', size);  
    }
}
Issue

This issue occurs when an array index falls outside the range [0...array_size-1] during array access.

Risk

Accessing an array outside its bounds is undefined behavior. You can read an unpredictable value or try to access a location that is not allowed and encounter a segmentation fault.

Fix

The fix depends on the root cause of the defect. For instance, you accessed an array inside a loop and one of these situations happened:

  • The upper bound of the loop is too large.

  • You used an array index that is the same as the loop index instead of being one less than the loop index.

To fix the issue, you have to modify the loop bound or the array index.

Another reason why an array index can exceed array bounds is a prior conversion from signed to unsigned integers. The conversion can result in a wrap around of the index value, eventually causing the array index to exceed the array bounds.

Often the result details (or source code tooltips in Polyspace as You Code™) show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show this event history, you can search for previous references of variables relevant to the defect using right-click options in the source code and find related events. See also Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface or Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access).

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example – Array Access Out of Bounds Error
#include <stdio.h>

void fibonacci(void)
{
    int i;
    int fib[10];
 
    for (i = 0; i < 10; i++) 
       {
        if (i < 2) 
            fib[i] = 1;
         else 
            fib[i] = fib[i-1] + fib[i-2];
       }

    printf("The 10-th Fibonacci number is %i .\n", fib[i]);    //Noncompliant
    /* Defect: Value of i is greater than allowed value of 9 */
}

The array fib is assigned a size of 10. An array index for fib has allowed values of [0,1,2,...,9]. The variable i has a value 10 when it comes out of the for-loop. Therefore, the printf statement attempts to access fib[10] through i.

Correction – Keep Array Index Within Array Bounds

One possible correction is to print fib[i-1] instead of fib[i] after the for-loop.

#include <stdio.h>

void fibonacci(void)
{
   int i;
   int fib[10];

   for (i = 0; i < 10; i++) 
    {
        if (i < 2) 
            fib[i] = 1;
        else 
            fib[i] = fib[i-1] + fib[i-2];
    }

    /* Fix: Print fib[9] instead of fib[10] */
    printf("The 10-th Fibonacci number is %i .\n", fib[i-1]); 
}

The printf statement accesses fib[9] instead of fib[10].

Issue

This issue occurs when a pointer is dereferenced outside its bounds.

When a pointer is assigned an address, a block of memory is associated with the pointer. You cannot access memory beyond that block using the pointer.

Risk

Dereferencing a pointer outside its bounds is undefined behavior. You can read an unpredictable value or try to access a location that is not allowed and encounter a segmentation fault.

Fix

The fix depends on the root cause of the defect. For instance, you dereferenced a pointer inside a loop and one of these situations happened:

  • The upper bound of the loop is too large.

  • You used pointer arithmetic to advance the pointer with an incorrect value for the pointer increment.

To fix the issue, you have to modify the loop bound or the pointer increment value.

Often the result details (or source code tooltips in Polyspace as You Code) show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show this event history, you can search for previous references of variables relevant to the defect using right-click options in the source code and find related events. See also Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface or Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access).

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example – Pointer access out of bounds error
int* Initialize(void)
{
 int arr[10];
 int *ptr=arr;

 for (int i=0; i<=9;i++)
   {
    ptr++;
    *ptr=i; //Noncompliant
    /* Defect: ptr out of bounds for i=9 */
   }

 return(arr);
}

ptr is assigned the address arr that points to a memory block of size 10*sizeof(int). In the for-loop, ptr is incremented 10 times. In the last iteration of the loop, ptr points outside the memory block assigned to it. Therefore, it cannot be dereferenced.

Correction — Check Pointer Stays Within Bounds

One possible correction is to reverse the order of increment and dereference of ptr.

int* Initialize(void)
{
 int arr[10];
 int *ptr=arr;

 for (int i=0; i<=9;i++)
     {
      /* Fix: Dereference pointer before increment */
      *ptr=i;
      ptr++;
     }

 return(arr);
}

After the last increment, even though ptr points outside the memory block assigned to it, it is not dereferenced more.

Issue

Array access with tainted index detects reading or writing to an array by using a tainted index that has not been validated.

Risk

The index might be outside the valid array range. If the tainted index is outside the array range, it can cause:

  • Buffer underflow/underwrite — writing to memory before the beginning of the buffer.

  • Buffer overflow — writing to memory after the end of a buffer.

  • Over-reading a buffer — accessing memory after the end of the targeted buffer.

  • Under-reading a buffer, or accessing memory before the beginning of the targeted buffer.

An attacker can use an invalid read or write operation create to problems in your program.

Fix

Before using the index to access the array, validate the index value to make sure that it is inside the array range.

Example - Use Index to Return Buffer Value
#include <stdlib.h>
#include <stdio.h>
#define SIZE100 100
extern int tab[SIZE100];
static int tainted_int_source(void) {
  return strtol(getenv("INDEX"),NULL,10);
}
int taintedarrayindex(void) {
	int num = tainted_int_source();
    return tab[num];   //Noncompliant
}

In this example, the index num accesses the array tab. The index num is obtained from an unsecure source and the function taintedarrayindex does not check to see if num is inside the range of tab.

Correction — Check Range Before Use

One possible correction is to check that num is in range before using it.

#include <stdlib.h>
#include <stdio.h>
#define SIZE100 100
extern int tab[SIZE100];
static int tainted_int_source(void) {
	return strtol(getenv("INDEX"),NULL,10);
}
int taintedarrayindex(void) {
	int num = tainted_int_source();
	if (num >= 0 && num < SIZE100) {
		return tab[num]; 
	} else {
		return -1;
	}
}

Issue

Pointer dereference with tainted offset detects pointer dereferencing, either reading or writing, using an offset variable from an unknown or unsecure source.

This check focuses on dynamically allocated buffers. For static buffer offsets, see Array access with tainted index.

Risk

The index might be outside the valid array range. If the tainted index is outside the array range, it can cause:

  • Buffer underflow/underwrite, or writing to memory before the beginning of the buffer.

  • Buffer overflow, or writing to memory after the end of a buffer.

  • Over reading a buffer, or accessing memory after the end of the targeted buffer.

  • Under-reading a buffer, or accessing memory before the beginning of the targeted buffer.

An attacker can use an invalid read or write to compromise your program.

Fix

Validate the index before you use the variable to access the pointer. Check to make sure that the variable is inside the valid range and does not overflow.

Example - Dereference Pointer Array
#include <stdio.h>
#include <stdlib.h>
enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};
extern void read_pint(int*);

int taintedptroffset(void) {
    int offset;
    scanf("%d",&offset);
    int* pint = (int*)calloc(SIZE10, sizeof(int));
    int c = 0;
    if(pint) {
        /* Filling array */
        read_pint(pint);
        c = pint[offset]; //Noncompliant
        free(pint);
    }
    return c;
}

In this example, the function initializes an integer pointer pint. The pointer is dereferenced using the input index offset. The value of offset could be outside the pointer range, causing an out-of-range error.

Correction — Check Index Before Dereference

One possible correction is to validate the value of offset. Continue with the pointer dereferencing only if offset is inside the valid range.

#include <stdlib.h>
#include <stdio.h>
enum {
    SIZE10  =  10,
    SIZE100 = 100,
    SIZE128 = 128
};
extern void read_pint(int*);

int taintedptroffset(void) {
    int offset;
    scanf("%d",&offset);
    int* pint = (int*)calloc(SIZE10, sizeof(int));
    int c = 0;
    if (pint) {
        /* Filling array */
        read_pint(pint);
        if (offset>0 && offset<SIZE10) {
            c = pint[offset];
        }
        free(pint);
    }
    return c;
}
Issue

This issue occurs when you invoke fread() using a set of arguments that results in a buffer overflow. Consider the syntax of fread():

size_t fread( void *restrict buffer, size_t size, size_t count, FILE *restrict stream );
When calling fread(), the size of the memory block pointed to by buffer attempts to hold count number of elements of size size. Polyspace reports a violation if this condition is true:
sizeof(buffer) < size * count

Risk

Calling fread() when size * count is greater than the size of buffer in bytes results in a buffer overflow, which is undefined behavior.

Fix

When calling fread(), check that the size of buffer, in bytes, is equal to or greater than size * count.

Example

In this example, the function foo() calls fread() to read contents of the file stream file into the buffer buf. The function foo() calculates the number of elements of buf as the number of bytes in buf, or sizeof(buf). But each element of buf is a wide character, which can be greater than one byte in size. As a result, sz * numel can be greater than the size of buf in bytes and the call to fread() can result in a buffer overflow. Polyspace reports a violation.

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <wchar.h>

#define BUFSZ 1024
void foo(FILE *file){
    //...
    // Create buffer
	wchar_t buf[BUFSZ];
    // calculate size of each element
	const size_t sz = sizeof(*buf);
    // count the number of elements of buf as the number of bytes of buf
	const size_t numel = sizeof(buf);
    // Call fread to read from *file into buffer
	size_t nread = fread(buf, sz, numel, file);   // Noncompliant      

	/* ... */

}

Correction

To fix this issue, calculate the numel parameter with the correct assumption about the size of the elements:

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <wchar.h>

#define BUFSZ 1024
void foo(FILE *file){
    //...
    // Create buffer
	wchar_t buf[BUFSZ];
    // calculate size of each element
	const size_t sz = sizeof(*buf);
    // count the number of elements
	const size_t numel = sizeof(buf)/sz;
    // Call fread to read from *file into buffer
	size_t nread = fread(buf, sz, numel, file);   // Compliant      

	/* ... */

}

Issue

Mismatch between data length and size looks for memory copying functions such as memcpy, memset, or memmove. If you do not control the length argument and data buffer argument properly, Bug Finder raises a defect.

Risk

If an attacker can manipulate the data buffer or length argument, the attacker can cause buffer overflow by making the actual data size smaller than the length.

This mismatch in length allows the attacker to copy memory past the data buffer to a new location. If the extra memory contains sensitive information, the attacker can now access that data.

This defect is similar to the SSL Heartbleed bug.

Fix

When copying or manipulating memory, compute the length argument directly from the data so that the sizes match.

Example - Copy Buffer of Data
#include <stdlib.h>
#include <string.h>

typedef struct buf_mem_st {
    char *data;
    size_t max;     /* size of buffer */
} BUF_MEM;

extern BUF_MEM beta;

int cpy_data(BUF_MEM *alpha)
{
    BUF_MEM *os = alpha;
    int num, length;

    if (alpha == 0x0) return 0;
    num = 0;

    length = *(unsigned short *)os->data;
    memcpy(&(beta.data[num]), os->data + 2, length); //Noncompliant

    return(1);
}

This function copies the buffer alpha into a buffer beta. However, the length variable is not related to data+2.

Correction — Check Buffer Length

One possible correction is to check the length of your buffer against the maximum value minus 2. This check ensures that you have enough space to copy the data to the beta structure.

#include <stdlib.h>
#include <string.h>

typedef struct buf_mem_st {
    char *data;
    size_t max;     /* size of buffer */
} BUF_MEM;

extern BUF_MEM beta;

int cpy_data(BUF_MEM *alpha)
{
    BUF_MEM *os = alpha;
    int num, length;

    if (alpha == 0x0) return 0;
    num = 0;

    length = *(unsigned short *)os->data;
    if (length<(os->max -2)) {
        memcpy(&(beta.data[num]), os->data + 2, length); 
    }

    return(1);

}
Issue

Invalid use of standard library memory routine occurs when a memory library function is called with invalid arguments. For instance, the memcpy function copies to an array that cannot accommodate the number of bytes copied.

Risk

Use of a memory library function with invalid arguments can result in issues such as buffer overflow.

Fix

The fix depends on the root cause of the defect. Often the result details show a sequence of events that led to the defect. You can implement the fix on any event in the sequence. If the result details do not show the event history, you can trace back using right-click options in the source code and see previous related events. See also Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example - Invalid Use of Standard Library Memory Routine Error
#include <string.h>
#include <stdio.h>

char* Copy_First_Six_Letters(void)
 {
  char str1[10],str2[5];

  printf("Enter string:\n");
  scanf("%9s",str1);

  memcpy(str2,str1,6);  //Noncompliant
  /* Defect: Arguments of memcpy invalid: str2 has size < 6 */

  return str2;
 }

The size of string str2 is 5, but six characters of string str1 are copied into str2 using the memcpy function.

Correction — Call Function with Valid Arguments

One possible correction is to adjust the size of str2 so that it accommodates the characters copied with the memcpy function.

#include <string.h>
#include <stdio.h>

char* Copy_First_Six_Letters(void)
 {
  /* Fix: Declare str2 with size 6 */
  char str1[10],str2[6]; 

  printf("Enter string:\n");
  scanf("%9s",str1);

  memcpy(str2,str1,6);
  return str2;
 }
Issue

Buffer overflow from incorrect string format specifier occurs when the format specifier argument for functions such as sscanf leads to an overflow or underflow in the memory buffer argument.

Risk

If the format specifier specifies a precision that is greater than the memory buffer size, an overflow occurs. Overflows can cause unexpected behavior such as memory corruption.

Fix

Use a format specifier that is compatible with the memory buffer size.

Example - Memory Buffer Overflow
#include <stdio.h>

void func (char *str[]) {
    char buf[32];
    sscanf(str[1], "%33c", buf); //Noncompliant
}

In this example, buf can contain 32 char elements. Therefore, the format specifier %33c causes a buffer overflow.

Correction — Use Smaller Precision in Format Specifier

One possible correction is to use a smaller precision in the format specifier.

#include <stdio.h>

void func (char *str[]) {
    char buf[32];
    sscanf(str[1], "%32c", buf);
}
Issue

This issue occurs when:

  • You perform string operations that require calling std::char_traits::length() on NULL, 0, or nullptr. Examples of such string operations are creating, appending, assigning, inserting, or replacing the string. For a list of operations that results in call to std::char_traits::length(), see STR51-CPP.

    This issue is a specific instance of the issue Null pointer, which causes violations of CERT C++: EXP34-C. Consider this code:

    std::string getString(); //returns nullptr
    void foo(){
        std::string str{getString()};//Defect
    }
    Construction of str requires an implicit call to std::char_traits::length(). Polyspace reports a violation because getString() returns a nullptr, which results in calling std::char_traits::length() on nullptr.

  • You perform certain string operations on a nonnull pointer to an uninitialized memory block. Consider this code:

    void foo() {
    
    	const char* uninitialized = (const char*)std::malloc(size*sizeof(char) + 1);;
    	 std::string tmp(uninitialized);  //Noncompliant
    } 
    Polyspace reports a violation of this rule when tmp is constructed by using the uninitialized memory in uninitialized.

A violation of this rule is not reported for stubbed functions.

Risk

Performing string operations that require calling std::char_traits::length() on NULL, 0, or nullptr might result in an undefined behavior. The function std::char_traits::length() dereferences the null pointer, which is an undefined behavior.

Performing string operations on uninitialized memory results in unexpected outcome and might result in bugs that are difficult to diagnose.

Fix

Check if the string object is a null pointer or an empty string before you perform string operations.

Example — String Operations Using Null Pointer

          #include <cstdlib>
#include <string>

int status;
const char *getInput()
{
    return status == 0 ? std::getenv("TMP") : nullptr;

}

void foo()
{
    status=1;
    const char *data = getInput();
    //...
    std::string str(data);   // Noncompliant
    str.append(data);        // Noncompliant
    str.assign(data);        // Noncompliant
    str.insert(0, data);     // Noncompliant
    str.replace(0, 1, data); // Noncompliant
}

In this example, the const char* object data is created by calling getInput(), and then various string operations are performed by using data. Polyspace reports a violation of this rule for each string operation because the function getInput() returns a nullptr which is then assigned to data.

Correction — Avoid Performing String Operation on Null Pointers

Modify getInput() so that the function does not return a nullptr.


          #include <cstdlib>
#include <string>

int status;
const char *getInput()
{
    return status == 0 ? std::getenv("TMP") : "";

}

void foo()
{
    status=1;
    const char *data = getInput();
    //...
    std::string str(data);   // Compliant
    str.append(data);        // Compliant
    str.assign(data);        // Compliant
    str.insert(0, data);     // Compliant
    str.replace(0, 1, data); // Compliant
}
Issue

Invalid use of standard library string routine occurs when a string library function is called with invalid arguments.

Risk

The risk depends on the type of invalid arguments. For instance, using the strcpy function with a source argument larger than the destination argument can result in buffer overflows.

Fix

The fix depends on the standard library function involved in the defect. In some cases, you can constrain the function arguments before the function call. For instance, if the strcpy function:

char * strcpy(char * destination, const char* source);
tries to copy too many bytes into the destination argument compared to the available buffer, constrain the source argument before the call to strcpy. In some cases, you can use an alternative function to avoid the error. For instance, instead of strcpy, you can use strncpy to control the number of bytes copied. See also Interpret Polyspace Bug Finder Results in Polyspace Platform User Interface.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Example - Invalid Use of Standard Library String Routine Error
 #include <string.h>
 #include <stdio.h>
 
 char* Copy_String(void)
 {
  char *res;
  char gbuffer[5],text[20]="ABCDEFGHIJKL"; 

  res=strcpy(gbuffer,text);  //Noncompliant 
  /* Error: Size of text is less than gbuffer */

  return(res);
 }

The string text is larger in size than gbuffer. Therefore, the function strcpy cannot copy text into gbuffer.

Correction — Use Valid Arguments

One possible correction is to declare the destination string gbuffer with equal or larger size than the source string text.

#include <string.h>
 #include <stdio.h>
 
 char* Copy_String(void)
 {
  char *res;
  /*Fix: gbuffer has equal or larger size than text */
  char gbuffer[20],text[20]="ABCDEFGHIJKL";

  res=strcpy(gbuffer,text);

  return(res);
 }
Issue

Destination buffer overflow in string manipulation occurs when certain string manipulation functions write to their destination buffer argument at an offset greater than the buffer size.

For instance, when calling the function sprintf(char* buffer, const char* format), you use a constant string format of greater size than buffer.

Risk

Buffer overflow can cause unexpected behavior such as memory corruption or stopping your system. Buffer overflow also introduces the risk of code injection.

Fix

One possible solution is to use alternative functions to constrain the number of characters written. For instance:

  • If you use sprintf to write formatted data to a string, use snprintf, _snprintf or sprintf_s instead to enforce length control. Alternatively, use asprintf to automatically allocate the memory required for the destination buffer.

  • If you use vsprintf to write formatted data from a variable argument list to a string, use vsnprintf or vsprintf_s instead to enforce length control.

  • If you use wcscpy to copy a wide string, use wcsncpy, wcslcpy, or wcscpy_s instead to enforce length control.

Another possible solution is to increase the buffer size.

Example - Buffer Overflow in sprintf Use
#include <stdio.h>

void func(void) {
    char buffer[20];
    char *fmt_string = "This is a very long string, it does not fit in the buffer";

    sprintf(buffer, fmt_string); //Noncompliant
}

In this example, buffer can contain 20 char elements but fmt_string has a greater size.

Correction — Use snprintf Instead of sprintf

One possible correction is to use the snprintf function to enforce length control.

#include <stdio.h>

void func(void) {
    char buffer[20];
    char *fmt_string = "This is a very long string, it does not fit in the buffer";

    snprintf(buffer, 20, fmt_string);
}
Issue

Destination buffer underflow in string manipulation occurs when certain string manipulation functions write to their destination buffer argument at a negative offset from the beginning of the buffer.

For instance, for the function sprintf(char* buffer, const char* format), you obtain the buffer from an operation buffer = (char*)arr; ... buffer += offset;. arr is an array and offset is a negative value.

Risk

Buffer underflow can cause unexpected behavior such as memory corruption or stopping your system. Buffer underflow also introduces the risk of code injection.

Fix

If the destination buffer argument results from pointer arithmetic, see if you are decrementing a pointer. Fix the pointer decrement by modifying either the original value before decrement or the decrement value.

Example - Buffer Underflow in sprintf Use
#include <stdio.h>
#define offset -2

void func(void) {
    char buffer[20];
    char *fmt_string ="Text";

    sprintf(&buffer[offset], fmt_string);      //Noncompliant
}

In this example, &buffer[offset] is at a negative offset from the memory allocated to buffer.

Correction — Change Pointer Decrementer

One possible correction is to change the value of offset.

#include <stdio.h>
#define offset 2

void func(void) {
    char buffer[20];
    char *fmt_string ="Text";

    sprintf(&buffer[offset], fmt_string);     
}

Check Information

Category: Memory Buffer Errors
PQL Name: std.cwe_native.R788

Version History

Introduced in R2026a