2013-05-04 57 views
0

我在運行時分配了兩個16位指針,以便將一些長雙倍存儲到閃存中(使用Microchip DEE閃存仿真庫)。代碼工作正常,並正確回憶保存的值,但是如果我在malloc()的指針上使用free(),則代碼在下一個malloc()調用處發生段錯誤(在另一個函數中,在另一段代碼中) 。PIC24上的免費()段錯誤

void readMicCalData(Microphone* pMicRead) 
{ 
/* Allocate space for 2*16-bit pointers */ 
int16_t* tempFlashBuffer = (int16_t*)malloc(sizeof(int16_t)); 
int16_t* tempFlashBuffer2 = (int16_t*)malloc(sizeof(int16_t)); 

if ((tempFlashBuffer == NULL) || (tempFlashBuffer2 == NULL)) { 
    debugMessage("\n\rHEAP> Failed to allocate memory for flash buffer!\n\r",1); 
} 

/* Increment through 2-byte blocks */ 
wc1 = RCM_MIC_CAL_START_ADDRESS; 
while(wc1 < RCM_MIC_CAL_END_ADDRESS) { 

    /* Init pointer to lowest 16-bits of 32-bit value e.g. 0x0D90 */ 
    tempFlashBuffer = (int16_t*) &pMicRead->Factor_dB[i4]; 

    /* Save pointer and increment to next 16-bit address e.g. 0x0D92 */ 
    tempFlashBuffer2 = tempFlashBuffer + 1; 

    /* Read first 16-bit value */ 
    *tempFlashBuffer = DataEERead(wc1); 

    /* Catch 0xFFFF and set to zero. Otherwise the float becomes NaN. */ 
    if (*tempFlashBuffer == 0xFFFF) { *tempFlashBuffer = 0; } 

    /* Read next 16-bits of value */ 
    *tempFlashBuffer2 = DataEERead(wc1 + 1); 

    if (*tempFlashBuffer2 == 0xFFFF) { *tempFlashBuffer2 = 0; } 

    /* Move to next 2*16-bit block of memory */ 
    wc1 = wc1 + 2; 

    /* Move to next saved mic. cal. frequency */ 
    i4++; 
} 

/* Free memory */ 
free(tempFlashBuffer); 
free(tempFlashBuffer2); 
} 

tempFlashBuffer2賦值可以計算爲增量嗎?因此,我不是免費的()從malloc()分配相同的指針?

如果我沒有釋放()兩個指針,代碼運行良好,並沒有看到任何段錯誤(至少不在短期!)。

+1

爲什麼你在這裏mallocing?似乎你只是在輸入循環時立即重新分配它們。 – 2013-05-04 07:26:27

+0

啊。我想我已經陷入了困境。你是對的。 – njt 2013-05-04 07:33:44

+0

未編輯。由於代碼與所給回覆相關。 – hmjd 2013-05-04 07:40:16

回答

1

傳遞到free()的指針必須是先前調用malloc()calloc()realloc()所返回的指針。當你改變指針值時,這不是這種情況,導致未定義的行爲。從部分7.20.3.2自由函數C99標準的

自由功能使空間ptr指向被解除分配,即,由 可用於進一步的分配。如果ptr是空指針,則不會發生任何操作。 否則,如果 參數與先前由calloc,malloc或realloc函數返回的指針不匹配,或者空間已被釋放或realloc調用釋放,則行爲未定義。