【问题标题】:malloc error - incorrect checksum for freed object - object was probably modified after being freedmalloc 错误 - 已释放对象的校验和不正确 - 对象可能在被释放后被修改
【发布时间】:2013-02-25 13:33:43
【问题描述】:

我正在尝试获取 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];

}

谢谢!!

【问题讨论】:

    标签: ios objective-c memory-management nsdata


    【解决方案1】:

    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 为奇数。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2012-03-17
      相关资源
      最近更新 更多