Buffer overflow

A buffer overflow error occurs when a program unintentionally writes to a memory area that's out of bounds for the buffer it intended to write to.

Consequences

A buffer overflow generates the following runtime errors:

Detecting the error

The Memory Analysis tool can detect a limited number of possible buffer overflows with following conditions:

strcat strdup strncat strcmp strncmp strcpy strncpy strlen strchr strrchr index rindex strpbrk strspn strcspn strstr strtok memccpy memchr memmove memcpy memcmp memset bcopy bzero bcmp

Enabling error detection

To enable error detection for a buffer overflow or underflow:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select Enable error detection checkbox.
  3. To detect an immediate overflow, select Verify parameters in string and memory functions.
  4. To detect a small overflow in block's memory overhead area, select Enabled bounds checking (where possible).
  5. To detect a corrupted heap, caused by overflowing other regions, select Perform full heap integrity check on every allocation/deallocation.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Summary of error messages for Memory Analysis.

How to address buffer overflow errors

Locate the code where the actual overflow occurred. Ensure that the size of the memory region is always accompanied by the pointer itself, verify all unsafe operations, and that the memory region is large enough to accommodate the data going into that location.

Example

The following code shows an example of a buffer overflow trapped by a library function:

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(12);
  strcpy(ptr,"Hello World!");
  return 0;
}

The following code shows an example of a buffer overflow trapped by a post-heap check in a free function:

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(12);
  ptr[12]=0;
  free(pre);
  return 0;
}