Ios malloc错误-已释放对象的校验和不正确-对象可能在被释放后被修改
我正在尝试获取NSData对象的子数据,同时根据我个人的需要按某个值获取多个字节 实际上,这会影响.wav声音文件的音量 但在调用以下函数几次之后,在malloc语句中出现了malloc错误Ios malloc错误-已释放对象的校验和不正确-对象可能在被释放后被修改,ios,objective-c,memory-management,nsdata,Ios,Objective C,Memory Management,Nsdata,我正在尝试获取NSData对象的子数据,同时根据我个人的需要按某个值获取多个字节 实际上,这会影响.wav声音文件的音量 但在调用以下函数几次之后,在malloc语句中出现了malloc错误 +(NSData *) subDataOfData: (NSData *) mainData withRange:(NSRange) range volume (CGFloat) volume { // here is the problematic line: Byte * soundWi
+(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];
}
+(NSData*)子数据的数据:(NSData*)带范围的主数据:(NSRange)范围卷(CGFloat)卷
{
//下面是有问题的一行:
字节*soundWithVolumeBytes=(字节*)malloc(range.length);
字节*mainSoundFileBytes=(字节*)[mainData字节];
对于(int i=range.location;i sampleInt16Value=(sampleInt16Value当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
为奇数,则最后一次迭代可能会访问超过缓冲区末尾的一个字节