The code calls sizeof() on a malloced pointer type, which
always returns the wordsize/8. This can produce an unexpected result if the
programmer intended to determine how much memory has been
allocated.
Time of Introduction
Implementation
Applicable Platforms
Languages
C
C++
Common Consequences
Scope
Effect
Integrity
This error can often cause one to allocate a buffer that is much
smaller than what is needed, leading to resultant weaknesses such as
buffer overflows.
Likelihood of Exploit
High
Demonstrative Examples
Example 1
Care should be taken to ensure sizeof returns the size of the data
structure itself, and not the size of the pointer to the data
structure.
In this example, sizeof(foo) returns the size of the pointer.
(Bad Code)
C and C++
double *foo;
...
foo = (double *)malloc(sizeof(foo));
In this example, sizeof(*foo) returns the size of the data structure
and not the size of the pointer.
(Good Code)
C and C++
double *foo;
...
foo = (double *)malloc(sizeof(*foo));
Potential Mitigations
Phase
Description
Implementation
use expressions such as "sizeof(*pointer)" instead of
"sizeof(pointer)", unless you intend to run sizeof() on a pointer type
to gain some platform independence or if you are allocating a variable
on the stack.
Other Notes
The use of sizeof() on a pointer can sometimes generate useful
information. An obvious case is to find out the wordsize on a platform. More
often than not, the appearance of sizeof(pointer) indicates a bug.
Weakness Ordinalities
Ordinality
Description
Primary
(where the
weakness exists independent of other weaknesses)