malloc error - incorrect checksum for freed object - object was probably modified after being freed

心不动则不痛 提交于 2020-01-06 01:53:17

问题


I'm trying to get sub data of NSData object and at the same time multiple bytes by some value for my personal need .

actually this affect the volume of .wav sound file .

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];

}

Thanks !!


回答1:


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] = ...

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] = ...

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.



来源:https://stackoverflow.com/questions/15068206/malloc-error-incorrect-checksum-for-freed-object-object-was-probably-modifie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!