malloc错误 – 对于释放的对象不正确的校验和 – 对象可能在被释放后被修改

我试图获取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.locationrange.location+range.length-1 ,但分配的范围仅从零到range.length 。 你需要改变行

 soundWithVolumeBytes[i-range.location] = ... soundWithVolumeBytes[i+1-range.location] = ... 

另外,由于你增加了2,所以在range.location+range.length是奇数的情况下,最后一次迭代可能会访问缓冲区末尾的一个字节。