Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: REM Cost Reform

Integer values The types of integer expressions used as a size argument arguments to malloc(), calloc(), or reallocrealloc(), or aligned_alloc() must be valid and large enough to contain have sufficient range to represent the size of the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur. Incorrect size arguments, inadequate range checking, integer overflow, or truncation can result in the allocation of an inadequately sized buffer. The programmer must ensure that size arguments to memory allocation functions allocate sufficient memory

Typically, the amount of memory to allocate will be the size of the type of object to allocate. When allocating space for an array, the size of the object will be multiplied by the bounds of the array. When allocating space for a structure containing a flexible array member, the size of the array member must be added to the size of the structure. (See MEM33-C. Allocate and copy structures containing a flexible array member dynamically.) Use the correct type of the object when computing the size of memory to allocate.

STR31-C. Guarantee that storage for strings has sufficient space for character data and the null terminator is a specific instance of this rule.

Noncompliant Code Example (

...

Pointer)

In this noncompliant code example, num_blocks is multiplied by 16 and the result is stored in the alloc.inadequate space is allocated for a struct tm object because the size of the pointer is being used to determine the size of the pointed-to object:

Code Block
bgColor#FFcccc
langc
#include <stdlib.h>
#include <time.h>
 
struct tm *make_tm(int year, int mon, int day, int hour,
                   int min, int sec) {
  struct tm *tmb;
  tmb = (struct tm *)malloc(sizeof(tmb));
enum { BLOCKSIZE = 16 };
/* ... */
void *alloc_blocks(size_t num_blocks) {
  if (num_blockstmb == 0NULL) {
    return NULL;
  }
  *tmb = (struct unsignedtm) long{
 long alloc = num.tm_blockssec *= BLOCKSIZE ;
  return (alloc < UINT_MAX)
     ? malloc(num_blocks * BLOCKSIZE )
     : NULL;
}

If size_t is represented as a 32-bit unsigned value and unsigned long long is represented as a 64-bit unsigned value, for example, the result of this multiplication can still overflow because the actual multiplication is a 32-bit operation. As a result, the value stored in alloc will always be less than UINT_MAX.

If both size_t and unsigned long long types are represented as a 64-bit unsigned value, the result of the multiplication operation may not be representable as an unsigned long long value. See INT35-C. Evaluate integer expressions in a larger size before comparing or assigning to that size for more information on upcasting.

Compliant Solution (Integer Overflow)

In this compliant solution, the integer values passed as size arguments to memory allocation functions are of the correct size and have not been altered due to integer overflow (INT32-C. Ensure that operations on signed integers do not result in overflow) or truncation (INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data).

Code Block
bgColor#ccccff

enum { BLOCKSIZE = 16 };
/* ... */
void *alloc_blocks(size_t num_blocks) {
  if (num_blocks == 0 || num_blocks > SIZE_MAX / BLOCKSIZE)
    return NULL;
  return malloc(num_blocks * BLOCKSIZE);
}

This example checks the value of num_blocks to make sure the subsequent multiplication operation cannot result in an integer overflow. The code also ensures that num_blocks is not equal to zero (see MEM04-C. Do not perform zero length allocations).

Noncompliant Code Example (Range Checking)

In this noncompliant code example, the string referenced by str and the string length represented by len originate from untrusted sources. The length is used to perform a memcpy() into the fixed-size static array buf. The len variable is guaranteed to be less than BUFF_SIZE. However, because len is declared as an int, it can have a negative value that would bypass the check. The memcpy() function implicitly converts len to an unsigned size_t type, and the resulting operation results in a buffer overflow.

Code Block
bgColor#FFcccc

int len;
char *str;
char buf[BUFF_SIZE];

/* ... */
if (len < BUFF_SIZE){
  memcpy(buf, str, len);
}
/* ... */

Compliant Solution (Range Checking)

In this compliant solution, len is declared as a size_t so there is no possibility of this variable having a negative value and bypassing the range check.

Code Block
bgColor#ccccff

size_t len;
char *str;
char buf[BUFF_SIZE];

/* ... */
if (len < BUFF_SIZE){
  memcpy(buf, str, len);
}
/* ... */

See INT01-C. Use rsize_t or size_t for all integer values representing the size of an object for more information on representing the size of objects.

sec, .tm_min = min, .tm_hour = hour,
    .tm_mday = day, .tm_mon = mon, .tm_year = year
  };
  return tmb;
}

Compliant Solution (Pointer)

 In this compliant solution, the correct amount of memory is allocated for the struct tm object. When allocating  space for a single object, passing the (dereferenced) pointer type to the sizeof operator is a simple way to allocate sufficient memory. Because the sizeof operator does not evaluate its operand, dereferencing an uninitialized or null pointer in this context is well-defined behavior.

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <time.h>
 
struct tm *make_tm(int year, int mon, int day, int hour,
                   int min, int sec) {
  struct tm *tmb;
  tmb = (struct tm *)malloc(sizeof(*tmb));
  if (tmb == NULL) {
    return NULL;
  }
  *tmb = (struct tm) {
    .tm_sec = sec, .tm_min = min, .tm_hour = hour,
    .tm_mday = day, .tm_mon = mon, .tm_year = year
  };
  return tmb;
}

Noncompliant Code Example (Integer

...

)

In this noncompliant code example, an array of of long is  is allocated and assigned to p. However, to pThe code attempts to check for unsigned integer overflow in compliance with INT30-C. Ensure that unsigned integer operations do not wrap and also ensures that len is not equal to zero. (See MEM04-C. Beware of zero-length allocations.) However, because sizeof(int) is  is used to size the allocated memory. If compute the size, and not sizeof(long), an insufficient amount of memory can be allocated on implementations where sizeof(long) is  is larger than than sizeof(int) then an insufficient amount of memory is allocated, and filling the array can cause a heap buffer overflow.

Code Block
bgColor#FFcccc
langc
#include <stdint.h>
#include <stdlib.h>
 
void function(size_t len) {
   long *p;
   if (len == 0 || len > SIZE_MAX / sizeof(long)) {
      /* Handle overflow */
   }
   p = (long *)malloc(len * sizeof(int));
   if (p == NULL) {
      /* Handle error */
   }
   /* ... */
   free(p);
}

...

Compliant Solution (

...

Integer)

To correct the noncompliant code example, This compliant solution uses sizeof(long) is used to  to correctly size the memory allocation.:

Code Block
bgColor#ccccff
langccccffc
#include <stdint.h>
#include <stdlib.h>


void function(size_t len) {
   long *p;
   if (len == 0 || len > SIZE_MAX / sizeof(long)) {
      /* Handle overflow */
   }
   p = (long *)malloc(len * sizeof(long));
   if (p == NULL) {
      /* Handle error */
   }
   /* ... */
   free(p);
}

Compliant Solution (Integer)

Alternatively, sizeof(*p) can  can be used to properly size the allocation.:

Code Block
bgColor#ccccff
langccccffc
#include <stdint.h>
#include <stdlib.h>
 
void function(size_t len) {
   long *p;
   if (len == 0 || len > SIZE_MAX / sizeof(*p)) {
      /* handleHandle overflow */
   }
   p = (long *)malloc(len * sizeof(*p));
   if (p == NULL) {
      /*   handleHandle error */
   }
   /* ... */
   free(p);
}

...

Risk Assessment

Providing invalid size arguments to memory allocation functions can lead to buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process.

Rule

Severity

Likelihood

Remediation Cost

Detectable

Repairable

Priority

Level

MEM35-C

High

high

Probable

probable

No

high

No

P6

L2

Automated Detection

Fortify SCA Version 5.0 with CERT C Rule Pack can detect violations of this rule, except those involving the sizeof operator.

Coverity Prevent. The SIZECHECK checker finds memory allocations that are assigned to a pointer that reference objects larger than the allocated block. Coverity Prevent cannot discover all violations of this rule so further verification is necessary.

...

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V
malloc-size-insufficient

Partially checked

Besides direct rule violations, all undefined behaviour resulting from invalid memory accesses is reported by Astrée.

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-MEM35
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

ALLOC.SIZE.ADDOFLOW
ALLOC.SIZE.IOFLOW
ALLOC.SIZE.MULOFLOW
ALLOC.SIZE.SUBUFLOW
ALLOC.SIZE.TRUNC
IO.TAINT.SIZE
MISC.MEM.SIZE.BAD
LANG.MEM.BO
LANG.MEM.BU
LANG.STRUCT.PARITH
LANG.STRUCT.PBB
LANG.STRUCT.PPE
LANG.MEM.TBA
LANG.MEM.TO
LANG.MEM.TU

Addition overflow of allocation size
Addition overflow of allocation size
Multiplication overflow of allocation size
Subtraction underflow of allocation size
Truncation of allocation size
Tainted allocation size
Unreasonable size argument
Buffer Overrun
Buffer Underrun
Pointer Arithmetic
Pointer Before Beginning of Object
Pointer Past End of Object
Tainted Buffer Access
Type Overrun
Type Underrun

Compass/ROSE



Could check violations of this rule by examining the size expression to malloc() or memcpy() functions. Specifically, the size argument should be bounded by 0, SIZE_MAX, and, unless it is a variable of type size_t or rsize_t, it should be bounds-checked before the malloc() call. If the argument is of the expression a*b, then an appropriate check is

...

Code Block

...

if (a < SIZE_MAX / b && a > 0) ..

...

.

Coverity

Include Page
Coverity_V
Coverity_V

BAD_ALLOC_STRLEN

SIZECHECK (deprecated)

Partially implemented

Can find instances where string length is miscalculated (length calculated may be one less than intended) for memory allocation purposes. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary

Finds memory allocations that are assigned to a pointer that reference objects larger than the allocated block

Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

premium-cert-mem35-c
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C0696, C0701, C1069, C1071, C1073, C2840

DF2840, DF2841, DF2842, DF2843, DF2935, DF2936, DF2937, DF2938


Klocwork
Include Page
Klocwork_V
Klocwork_V

INCORRECT.ALLOC_SIZE
SV.TAINTED.ALLOC_SIZE


LDRA tool suite
Include Page
LDRA_V
LDRA_V
400 S, 487 S, 115 D
Enhanced enforcement
Splint3.1.1

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V

CERT_C-MEM35-a

Do not use sizeof operator on pointer type to specify the size of the memory to be allocated via 'malloc', 'calloc' or 'realloc' function

PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

433, 826

Partially supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule MEM35-C


Checks for:

  • Pointer access out of bounds
  • Memory allocation with tainted size

Rule partially covered.

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V531, V635, V781
RuleChecker

Include Page
RuleChecker_V
RuleChecker_V

malloc-size-insufficientPartially checked
TrustInSoft Analyzer

Include Page
TrustInSoft Analyzer_V
TrustInSoft Analyzer_V

mem_access

Exhaustively detects undefined behavior (see one compliant and one non-compliant example).

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as MEM35-CPP. Allocate sufficient memory for an object.

References

Wiki Markup
\[[Coverity 07|AA. C References#Coverity 07]\]
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory Management Functions"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "XYB Buffer Overflow in Heap"
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 190|http://cwe.mitre.org/data/definitions/190.html], "Integer Overflow (Wrap or Wraparound)," and [CWE ID 131|http://cwe.mitre.org/data/definitions/131.html], "Incorrect Calculation of Buffer Size"
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management," and Chapter 5, "Integer Security"

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT C Secure Coding StandardARR01-C. Do not apply the sizeof operator to a pointer when taking the size of an array
INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data
Prior to 2018-01-12: CERT: Unspecified Relationship
CERT C Secure Coding StandardINT32-C. Ensure that operations on signed integers do not result in overflowPrior to 2018-01-12: CERT: Unspecified Relationship
CERT C Secure Coding StandardINT18-C. Evaluate integer expressions in a larger size before comparing or assigning to that sizePrior to 2018-01-12: CERT: Unspecified Relationship
CERT C Secure Coding StandardMEM04-C. Beware of zero-length allocationsPrior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TR 24772:2013Buffer Boundary Violation (Buffer Overflow) [HCB]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961:2013Taking the size of a pointer to determine the size of the pointed-to type [sizeofptr]Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-131, Incorrect Calculation of Buffer Size2017-05-16: CERT: Rule subset of CWE
CWE 2.11CWE-6802017-05-18: CERT: Rule subset of CWE
CWE 2.11CWE-7892017-06-12: CERT: Partial overlap

CERT-CWE Mapping Notes

Key here for mapping notes

CWE-680 and MEM35-C

Intersection( INT32-C, MEM35-C) = Ø

CWE-680 = Union( MEM35-C, list) where list =


  • Overflowed buffers with inadequate sizes not produced by integer overflow


CWE-467 and MEM35-C

CWE-467 = Subset( MEM35-C)

CWE-789 and MEM35-C

Intersection( MEM35-C, CWE-789) =


  • Insufficient memory allocation on the heap


MEM35-C – CWE-789 =


  • Insufficient memory allocation with trusted value but incorrect calculation


CWE-789 - MEM35-C =


  • Sufficient memory allocation (possibly over-allocation) with untrusted value


CWE-120 and MEM35-C

Intersection( MEM35-C, CWE-120) = Ø

CWE-120 specifically addresses buffer overflow operations, which occur in the context of string-copying. MEM35-C specifically addresses allocation of memory ranges (some of which may be for subsequent string copy operations).

Consequently, they address different sections of code, although one (or both) may be responsible for a single buffer overflow vulnerability.

CWE-131 and MEM35-C


  • Intersection( INT30-C, MEM35-C) = Ø



  • CWE-131 = Union( MEM35-C, list) where list =



  • Miscalculating a buffer for a non-heap region (such as a variable-length array)


Bibliography

[Coverity 2007]
[Drepper 2006]Section 2.1.1, "Respecting Memory Bounds"
[Seacord 2013]Chapter 4, "Dynamic Memory Management"
Chapter 5, "Integer Security"
[Viega 2005]Section 5.6.8, "Use of sizeof() on a Pointer Type"
[xorl 2009]CVE-2009-0587: Evolution Data Server Base64 Integer Overflows


...

Image Added Image Added Image AddedImage Removed      08. Memory Management (MEM)      09. Input Output (FIO)