我在运行时分配了两个16位指针,以便将一些长双精度指针保存到闪存中(使用Microchip DEE闪存模拟库)。代码运行良好,并正确地调用保存的值,但是如果我在malloc()的d指针上使用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);
}如果我没有释放()这两个指针,代码就会运行得很好,也看不到任何段错误(至少短期内不会!)。
发布于 2013-05-04 15:26:15
传递给free()的指针必须是上一次调用malloc()、calloc()或realloc()返回的指针。这里的情况并非如此,因为您正在更改指针值,从而导致未定义的行为。从7.20.3.2节开始,C99标准的免费功能:
释放函数
使ptr指向的空间被释放,即可用于进一步的分配。如果ptr为空指针,则不会发生任何操作。否则,如果参数与早先由calloc、malloc或realloc函数返回的指针不匹配,或者如果空间已通过调用free或realloc释放,则行为是未定义的。
https://stackoverflow.com/questions/16371682
复制相似问题