我正在尝试获取 NSData 对象的子数据,同时根据我的个人需要按某个值获取多个字节。
实际上这会影响 .wav 声音文件的音量。
但是在对以下函数进行几次调用后,我在 malloc 语句中遇到了 malloc 错误。
+(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];
}
谢谢!!
最佳答案
当 range.location
的值不为零时,您的 for
循环会修改超出分配范围的位置。这些线
soundWithVolumeBytes[i] = ...
soundWithVolumeBytes[i+1] = ...
写入从range.location
到range.location+range.length-1
的位置,但分配的范围只是从零到range.length
。您需要将这些行更改为
soundWithVolumeBytes[i-range.location] = ...
soundWithVolumeBytes[i+1-range.location] = ...
此外,由于您递增了 2,如果 range.location+range.length
是奇数,最后一次迭代可能会访问缓冲区末尾之后的字节。
关于ios - malloc 错误 - 释放对象的校验和不正确 - 对象可能在释放后被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068206/