我正在尝试获取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];
}
谢谢!
答案 0 :(得分:2)
当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
为奇数的情况下,最后一次迭代可以访问缓冲区末尾的字节。