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

标签 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 * 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 是奇数,最后一次迭代可能会访问缓冲区末尾之后的字节。

关于ios - malloc 错误 - 释放对象的校验和不正确 - 对象可能在释放后被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15068206/

相关文章:

ios - 一起使用 Google Analytics SDK 和 Firebase SDK

android - Firebase:报告分析和崩溃数据以分离项目

iPhone SDK 字体

c# - 如何优化此算法中的内存使用?

c++ - 数组的动态分配

iphone - 使用基础 sdk 5.0 编译的应用程序可以在 iOS4.x 上运行吗?

iphone - 在 Resources 文件夹下添加 iOS 图标和启动图像

ios - 失败的断言`vertexFunction不能为零-在iPad iOS 9.0.2中加载SceneKit场景时出错

objective-c - IOS滑动删除和多行编辑导致按钮名称设置为默认

iphone - iPhone 上未收到服务器响应