2012-06-07 76 views
-2

下面的代碼嘗試使用fwrite將數據流保存到文件。第一個使用malloc的例子可以工作,但第二個例子中數據流是%70損壞的。有人可以向我解釋爲什麼第二個示例已損壞,我該如何補救它?使用memcpy和malloc導致數據流損壞

short int fwBuffer[1000000]; 
// short int *fwBuffer[1000000]; 
unsigned long fwSize[1000000]; 

// Not Working ********* 

if (dataFlow) { 
     size = sizeof(short int)*length*inchannels; 
     short int tmpbuffer[length*inchannels]; 
     int count = 0; 
     for (count = 0; count < length*inchannels; count++) 
     { 
      tmpbuffer[count] = (short int) (inbuffer[count]); 
     } 

     memcpy(&fwBuffer[saveBufferCount], tmpbuffer, sizeof(tmpbuffer)); 
     fwSize[saveBufferCount] = size; 

     saveBufferCount++; 
     totalSize += size; 
    } 
// Working *********** 

if (dataFlow) { 
    size = sizeof(short int)*length*inchannels; 
    short int *tmpbuffer = (short int*)malloc(size); 

    int count = 0; 
    for (count = 0; count < length*inchannels; count++) 
    { 
     tmpbuffer[count] = (short int) (inbuffer[count]); 
    } 

    fwBuffer[saveBufferCount] = tmpbuffer; 
    fwSize[saveBufferCount] = size; 

    saveBufferCount++; 
    totalSize += size; 
} 


// Write to file *********** 

    for (int i = 0; i < saveBufferCount; i++) { 
     if (isRecording && outFile != NULL) { 
    //  fwrite(fwBuffer[i], 1, fwSize[i],outFile); 
      fwrite(&fwBuffer[i], 1, fwSize[i],outFile); 
      if (fwBuffer[i] != NULL) { 
    //   free(fwBuffer[i]); 
      } 
      fwBuffer[i] = NULL; 
     } 
    }  
+1

你試圖讓這個代碼昨天在[this]中調試(http://stackoverflow.com/questions/10919377/malloc-free-in-this-code-crashing-why#comment14241485_10919377)的問題。我向你保證memcpy和malloc不是你問題的原因。建議您重寫代碼並減少問題的大小,而不是隻是在不同的僞裝下反覆發佈相同的問題。 – wadesworld

+0

我想知道爲什麼人們在爲MacOS/iOS編碼時完全忽略C++ ...是的,Objective-C和C++並不完全是「朋友」,但使用STL在低級別管理內存要容易得多。例如,在你的代碼中,你「發明了一個輪子」,與std :: vector非常相似。 – Gobra

+0

Wadesworld,這是一個不同的問題(同一個項目)與已更正的線程相關,但thx。另外memcpy在另一篇文章中沒有任何地方。 – user1440367

回答

1

您初始化size作爲

size = sizeof(short int) * length * inchannels; 

則聲明大小

short int tmpbuffer[size]; 

數組這已經是非常值得懷疑。爲什麼包含sizeof(short int)的大小,然後用這個大小聲明一個short int元素的數組?在這種情況下,你的陣列的字節大小是

sizeof(short int) * sizeof(short int) * length * inchannels 

sizeof(short int)在兩次因素。

由於上述原因,稍後僅初始化數組的元素(該元素不是整個數組)。但是,這仍然如下拷貝整個陣列的memcpy

memcpy(&fwBuffer[saveBufferCount], &tmpbuffer, sizeof (tmpbuffer)); 

(複製的數據的尾部分是垃圾)。我懷疑你正在複製sizeof(short int)倍以上的數據。收件人內存溢出並被損壞。

基於malloc的版本不會遇到此問題,因爲malloc -ed內存大小以字節爲單位指定,而不是在short int -s中指定。

如果你想以模擬碼的高版本的malloc行爲,你需要聲明你tmpbuffer作爲char元素的數組,而不是short int元素。

+0

我能夠在你的幫助下取得進展。以上是更新的代碼,但我仍然有一些腐敗。有什麼建議麼? – user1440367

+0

@ user1440367:我在代碼中看不到任何相關更改。我描述的問題仍然存在。 – AnT

+0

我將你的建議應用於上面的代碼。似乎一切都已正確初始化。 – user1440367

1

這有很好的機會崩潰

short int tmpbuffer[(short int)(size)]; 

第一規模可能過大,但然後截斷它,並具有任意大小的的結果可能不是你想要的。

編輯:嘗試編寫整個代碼沒有一個單一的演員。只有編譯器有機會告訴你是否有什麼問題。