A byte size made with sizeof is added to a pointer to wider elements, which scales it again

tx0/c:pointer-offset-scaled-twicerecommendedwarningreliability/memory-safetydepth fastbug, security, cwe-468

What it finds

int *p; ... p + i * sizeof(int): adding to a pointer already counts in elements, so a byte offset made with sizeof is multiplied by the size of an element a second time and the result points far past the place meant, often past the end of the buffer. p + i was meant, or arithmetic on a char * if the offset really is in bytes.

The pointer must be a variable the file declares as a pointer or array whose elements are certainly wider than a byte, and the offset sizeof itself or a product with a sizeof factor.

From the rule's source, pointer_offset_scaled_twice.rs.

Example from the rule's tests
#include <stddef.h>#include <stdint.h> uint32_t word_at(uint32_t *words, size_t i){  return *(words + i * sizeof(uint32_t));tx0 reports: this offset in bytes is scaled again by the size of what words points to} struct rec { int a, b; }; struct rec *skip(struct rec *r){  r += sizeof(struct rec);tx0 reports: this offset in bytes is scaled again by the size of what r points to  return r;} uint8_t byte_at(uint8_t *bytes, size_t i){  return *(bytes + i * sizeof(uint32_t));} uint32_t *by_count(uint32_t *words, size_t len){  return words + len / sizeof(uint32_t);} char *bytes_of(uint32_t *words, size_t i){  return (char *)words + i * sizeof(uint32_t);}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/c:pointer-offset-scaled-twice" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:pointer-offset-scaled-twice] reason="..."

tx0 explain tx0/c:pointer-offset-scaled-twice shows the same in the terminal. Found a false positive? Report it.