41 lines
1.4 KiB
Plaintext
41 lines
1.4 KiB
Plaintext
The ``++sizeof++`` operator returns the size, in bytes, of its operand, which can be an expression or a type.
|
|
|
|
|
|
Function parameters with array types automatically decay to pointers, so it is hazardous to call the ``++sizeof++`` operator on such variables.
|
|
|
|
|
|
Moreover, calling the ``++sizeof++`` operator on a variable with pointer type is typically a mistake. Usually the intent was to get the size of the pointed-to value instead.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,text]
|
|
----
|
|
void clear1(int array[]) {
|
|
for (size_t i = 0; i < sizeof(array) / sizeof(*array); i+=1) { // Noncompliant, type of array decays to int *, so sizeof(array) evaluates to sizeof(int *)
|
|
array[i] = 0;
|
|
}
|
|
}
|
|
|
|
void clear2(short *array, int count) {
|
|
memset(array, sizeof(array) * count); // Noncompliant, sizeof(array) evaluates to the size of a pointer to short and not of a short
|
|
}
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* https://www.securecoding.cert.org/confluence/x/6wE[CERT, ARR01-C] - Do not apply the sizeof operator to a pointer when taking the size of an array
|
|
* https://www.securecoding.cert.org/confluence/x/9YAyAQ[CERT, CTR01-CPP] - Do not apply the sizeof operator to a pointer when taking the size of an array
|
|
* https://cwe.mitre.org/data/definitions/467[MITRE, CWE-467] - Use of sizeof() on a Pointer Type
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|