Same pointer passed to free twice
ID |
objectivec.correctness.double_free |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
high |
Remediation Effort |
low |
Resource |
Resource Management |
Language |
Objective-C |
Description
Reports two free calls on the same pointer expression at the same block level, with no assignment to that pointer in between. The pair has to sit in one straight-line run: any closing brace between the two calls ends the region, so calls on opposite branches of an if, calls in two different methods, and a call after a guarded early return are not reported.
Rationale
The second free hands the allocator a block it already owns. That corrupts the free list rather than failing, so the process usually survives the call and misbehaves later, in unrelated code, when two subsequent allocations are handed the same address and quietly write over each other. The crash - if there is one - lands nowhere near the second free, which is why this costs far more to diagnose than to prevent.
The following code illustrates the pattern detected by this rule:
@implementation Buffer
- (void)releaseTwice:(char *)payload {
free(payload);
[self log:@"released"];
// FLAGGED: Same pointer passed to free twice
free(payload);
}
- (void)log:(NSString *)text { }
@end
Remediation
Delete the redundant call. Where both calls are on real paths, set the pointer to NULL immediately after freeing it, so a later free is a no-op and any dereference faults at the point of the bug instead of corrupting the heap. Give each allocation a single owner responsible for releasing it.