问题
I'm trying to get sub data of NSData object and at the same time multiple bytes by some value for my personal need .
actually this affect the volume of .wav sound file .
but i get after few calls to the following function a malloc error at the malloc statement .
+(NSData *) subDataOfData: (NSData *) mainData withRange:(NSRange) range volume (CGFloat) volume
{
// here is the problematic line:
Byte * soundWithVolumeBytes = (Byte*)malloc(range.length);
Byte * mainSoundFileBytes =(Byte *)[mainData bytes];
for (int i=range.location ; i< range.location + range.length; i=i+2)
{
// get the original sample
int16_t sampleInt16Value = 0;
sampleInt16Value = (sampleInt16Value<<8) + mainSoundFileBytes[i+1];
sampleInt16Value = (sampleInt16Value<<8) + mainSoundFileBytes[i];
//multiple sample
sampleInt16Value*=volume;
//store the sample
soundWithVolumeBytes[i] = (Byte)sampleInt16Value;
soundWithVolumeBytes[i+1] =(Byte) (sampleInt16Value>>8);
}
NSData * soundDataWithVolume = [[NSData alloc] initWithBytes:soundWithVolumeBytes length:range.length];
free(soundWithVolumeBytes);
return [soundDataWithVolume autorelease];
}
Thanks !!
回答1:
When the value of range.location
is non-zero, your for
loop modifies locations beyond what's allocated. These lines
soundWithVolumeBytes[i] = ...
soundWithVolumeBytes[i+1] = ...
write to locations from range.location
to range.location+range.length-1
, but the allocated range is only from zero to range.length
. You need to change the lines to
soundWithVolumeBytes[i-range.location] = ...
soundWithVolumeBytes[i+1-range.location] = ...
In addition, since you increment by two, the last iteration may access a byte past the end of the buffer in case the range.location+range.length
is odd.
来源:https://stackoverflow.com/questions/15068206/malloc-error-incorrect-checksum-for-freed-object-object-was-probably-modifie