When performing pointer arithmetic, the size of the value to add to a pointer is automatically scaled to the size of the pointer's type. For instance, when adding a value to a pointer to a four-byte integer, the value will be is scaled by a factor of four and then added to the pointer. Failing to understand how pointer arithmetic works can lead to miscalculations that result in serious errors, such as buffer overflows.
Non-Compliant Code Example
example taken from Dowd, non-compliant code example derived from \[[Dowd|AA. C References#Dowd 06]], {{buf_ptr}} is used to insert new integers into {{buf}}, which is an array of 1024 integers. If there is data to be inserted into {{buf}} (which is indicated by {{havedata()}}) and {{buf_ptr}} has not been incremented past {{buf + sizeof(buf)}}, |
then is inserted into buf
via value is stored at the address referenced by {{buf_ptr}}. However, the {{sizeof}} operator returns the total number of bytes in |
buf
, which, assuming {{buf}} which is 4096 bytes, assuming four-byte integers |
, is 4096 bytes then scaled to the size of an integer and added to {{buf}}. As a result, the check to make sure integers are not written past the end of {{buf}} is incorrect and a buffer overflow |
occurs Code Block |
---|
|
int buf[1024];
int *buf_ptr = buf;
while (havedata() && buf_ptr < buf + sizeof(buf))
{
*buf_ptr++ = parseint(getdata());
}
|
Compliant Code Solution
To correct In this examplecompliant solution, the size of buf
can be is added directly added to buf
and used as an upper bound. The integer literal is scaled to the size of an integer and the upper bound of buf
is checked correctly.
Code Block |
---|
|
int buf[1024];
int *buf_ptr = buf;
while (havedata() && buf_ptr < (buf+1024))
{
*buf_ptr++ = parseint(getdata());
}
|
...