2013-02-25 73 views
1

我試圖獲取NSData對象的子數據,並同時爲我的個人需要獲取一些值的多個字節。malloc錯誤 - 對於釋放的對象的錯誤校驗和 - 對象可能在被釋放後被修改

實際上這會影響.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]; 

} 

謝謝!!

回答

2

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

此外,由於你的兩個遞增,最後一次迭代可以過去的情況下range.location+range.length是奇數緩衝區的結束訪問一個字節。

+0

謝謝!真的幫了!!! – 2013-02-25 13:55:03

相關問題