malloc 错误 - 释放对象的校验和不正确 - 对象可能在被释放后被修改 [英] malloc error - incorrect checksum for freed object - object was probably modified after being freed
问题描述
我正在尝试获取 NSData 对象的子数据,同时根据我个人需要的某个值获取多个字节.
I'm trying to get sub data of NSData object and at the same time multiple bytes by some value for my personal need .
实际上这会影响 .wav 声音文件的音量.
actually this affect the volume of .wav sound file .
但是在对以下函数进行几次调用后,我在 malloc 语句中遇到了 malloc 错误.
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];
}
谢谢!!
推荐答案
当 range.location
的值不为零时,您的 for
循环会修改超出范围的位置分配.这些行
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] = ...
写入从range.location
到range.location+range.length-1
的位置,但分配的范围只有从零到range.length代码>.您需要将行更改为
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] = ...
此外,由于您增加了 2,如果 range.location+range.length
是奇数,最后一次迭代可能会访问缓冲区末尾之后的一个字节.
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.
这篇关于malloc 错误 - 释放对象的校验和不正确 - 对象可能在被释放后被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!