...
Non-compliant Code Example 1
This piece of code incorrectly uses the sizeof operator. When applied to a pointerIn this example, the sizeof operator returns the size of the pointer, not the size of the block of space the pointer refers to. As a result the call to malloc will return () returns a pointer to a block of memory equal in size to the size of a pointer (commonly 4 bytes). When the strcpy() is called a heap buffer overflow will occur.
...
Non-compliant Code Example 2
| Wiki Markup |
|---|
The sizeof operator can be used to compute the number of elements in an array as follows: {{sizeof (dis) / sizeof (dis\[0\])}}. The sizeof operator can also be used to calculate the size of variable length arrays. In the case of a variable length array, the operand is evaluated at runtime. Extreme care must be taken when using this particular programming idiom, however. |
| Code Block |
|---|
void f(int a[]) {
int i;
for (i = 0; i < sizeof (a) / sizeof (a[0]); i++) {
a[i] = 21;
}
}
int main(void) {
int dis[12];
f(dis);
}
|
| Wiki Markup |
|---|
In the following example {{sizeof (a) / sizeof (a[0])}} evaluates to 1 because int {{a\[\]}} is equivalent to {{int \*a}} in the function declaration. This allows {{f()}} to be passed an array of arbitrary length. |
Compliant Solution
This problem can be fixed by passing the size as a separate argument, as shown in the following example:
| Code Block |
|---|
void g(int a[], int size) {
int i;
for (i = 0; i < size; i++) {
a[i] = 21;
}
}
int main(void) {
int dis[12];
g(dis, sizeof (dis) / sizeof (dis[0]));
}
|
Care must be taken to ensure that the size is valid for the array. If these parameters can be manipulated by an attacker, this function will almost always result in an exploitable vulnerability.
...
In general, correcting issues regarding improper use of the sizeof operator requires that the programmer have a solid understanding of how sizeof works. Consider the following data types and variables:
| Code Block |
|---|
struct test_struct {
char c1,c2;
int *integer_ptr;
};
char array[10];
char * pointer = malloc(10);
char character;
struct test_struct structure;
struct test_struct struct_array[10];
|
...