Why is this an issue?
Given an expression e
of type T
, sizeof(e)
returns the size in bytes of T
. The
sizeof
operator results in a value of type size_t
. Also, sizeof(e)
has no side effects because e
is not evaluated. Therefore, sizeof(sizeof(e))
is equivalent to sizeof(size_t)
.
In other words, sizeof(sizeof(e))
always gives the same result and does not depend on e
, which is unlikely what was
expected.
How to fix it
This defect is usually the consequence of a typo, and the fix is to remove one level of sizeof
.
Code examples
Noncompliant code example
void function() {
char buffer[42];
char buffer2[sizeof(sizeof(buffer))]; // Noncompliant: a single sizeof() was intended
memcpy(buffer, "Hello, world!", strlen("Hello, world!")+1);
memcpy(buffer2, buffer, sizeof(buffer)); // Buffer overflow
}
Compliant solution
void function() {
char buffer[42];
char buffer2[sizeof(buffer)]; // Compliant
memcpy(buffer, "Hello, world!", strlen("Hello, world!")+1);
memcpy(buffer2, buffer, sizeof(buffer));
}
Resources
Documentation