Reputation: 18517
I've seen there are questions about malloc(0)
which yield this alert about allocation size. My question is that I am getting this alert with a size.
In my code:
midiFileEventCount is of type uint32_t
BASS_MIDI_EVENT is a struct
I get the alert on the line below. Before that line I check that midiFileEventCount
is non-zero. My app seems to run correctly. Am I doing something wrong here?
This is on iOS 7.1
midiFileEvents=(BASS_MIDI_EVENT*)malloc(midiFileEventCount*sizeof(BASS_MIDI_EVENT));
Log statements:
printf("midiFileEventCount %u \n", midiFileEventCount);
printf("BASS_MIDI_EVENT size: %lu \n", sizeof(BASS_MIDI_EVENT));
printf("midiFileEvents size: %lu \n", midiFileEventCount*sizeof(BASS_MIDI_EVENT));
Output:
midiFileEventCount 1684
BASS_MIDI_EVENT size: 20
midiFileEvents size: 33680
Upvotes: 0
Views: 2254
Reputation: 57188
So, this is probably a potential bug in your code. The analyzer is telling you that there is a possible code path in your function in which the size is zero. Consider the following methods:
- (void *)foo:(int)size {
return malloc(size);
}
- (void *)bar:(int)size {
if (size == 0) {
NSLog(@"got zero size!");
}
return malloc(size);
}
The first method will produce no analyzer results. The second will produce the same diagnostic you're seeing. The clang folks reason as follows: normally, a call to malloc will probably not have a zero size passed, so foo
is unlikely to be a problem. bar
, however, explicitly checks for a size of zero, and then continues to the malloc anyway. So, since you (the code writer) are clearly expecting that the size might be zero, it warns you that, in that case, you're mallocing zero bytes. (If you expand the diagnostic, it will show you exactly what assumptions it's making that are leading to a zero-sized allocation).
Of course, it's possible that you never actually call that method such that it produces a zero-sized malloc, but the analyzer only looks over smaller regions of code and notices "suspicious" patterns.
In the case of bar
above, you could resolve it by asserting or returning NULL in the case that zero is passed.
Upvotes: 3