c - PIC24 上的 Free() 段错误

标签 c malloc free pic

我在运行时分配了两个 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/

相关文章:

c++ - C 等同于 C++ delete[] (char *)

c - localtime_s取决于智利圣地亚哥时区的当前系统时间

C - 在没有外部库的情况下设置 Printf 坐标

c++ - 这个递归 va_arg 代码有什么问题?

c - 如何将 malloced 变量传递给结构到 C 中新创建的结构

c - 将 int 视为地址/指针

add 函数中的 C trie 内存泄漏

c - 我收到错误 "warning: assignment to ' char' from 'char *' made integer frompointer without a Cast”

c - 从二叉树中删除所有小于/大于 C 中给定值的值?

c - strlen 和释放内存