我在运行时分配了两个 16 位指针,以便将一些长 double 保存到闪存(使用 Microchip DEE 闪存仿真库)。代码工作正常,并正确调用保存的值,但如果我在 malloc() 指针上使用 free(),则代码在下一次 malloc() 调用时出现段错误(在另一个函数中,在代码的另一部分中) .
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 分配可以算作增量吗?因此我没有 free()ing 从 malloc() 分配的同一指针?
如果我不 free() 这两个指针,代码运行良好并且不会出现任何段错误(至少在短期内不会出现!)。
最佳答案
传递给 free()
的指针必须是先前调用 malloc()
、calloc()
或 realloc()
。这里的情况并非如此,因为您正在更改指针值,从而导致未定义的行为。来自C99标准7.20.3.2自由函数部分:
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
关于c - PIC24 上的 Free() 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16371682/