Array element read through pointer arithmetic
ID |
objectivec.maintainability.array_index_bracket_notation |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Idiom |
Language |
Objective-C |
Description
Reports the dereference of a pointer plus an offset, (values + i), where the subscript form values[i] says the same thing. Both operands must be single names or literals, so a dotted or bracketed base such as (self.raw + i) is not reported. A * that multiplies - recognised by a literal, name, message send or subscript on its left - is not reported, and neither are occurrences inside a comment or a string literal.
Rationale
(values + i) and values[i] compile to the same address, but the first spells the address arithmetic out and the second names the intent. Spelled out, the reader has to confirm that the pointer is scaled by the element size and that the parentheses group as intended, and a mistake there - (values + i * sizeof(int)), or a missing pair of parentheses - is a memory error that reads as ordinary arithmetic. The subscript form cannot express the double-scaling mistake at all.
The following code illustrates the pattern detected by this rule:
@implementation Buffers
- (int)sum:(int *)values count:(int)count {
int total = 0;
for (int i = 0; i < count; i++) {
// FLAGGED: Array element read through pointer arithmetic
total += *(values + i);
}
// FLAGGED: Array element read through pointer arithmetic
int first = *(values + 0);
// FLAGGED: Array element read through pointer arithmetic
*(values + 1) = total;
// FLAGGED: Array element read through pointer arithmetic
NSLog(@"%d", *(values + count));
return total + first;
}
- (int)factor {
return 3;
}
@end