使用free()后,malloc调用PIC32崩溃(错误指针)

时间:2015-07-07 13:40:21

标签: c malloc free pic32

我正在处理涉及PIC32MX220f032b的项目,其中我必须使用动态内存分配在链表中声明未知数量的结构。

malloc调用,一切正常,直到我继续实现删除数据。 我们的想法是分配一些结构并用数据填充它们(一些通过指针)。在某个时间点,所有已知的结构都被释放,声明了新结构。

第一次测试仅分配了大约三轮,直到内存耗尽(可理解)。但是当我实现一个释放数据结构的函数时,malloc就不再起作用了。它的函数调用崩溃了pic并用指针错误将其发送到异常处理程序。但我无法弄清楚为什么......

我使用以下结构:

typedef struct image_element
{
    unsigned char conditional;
    unsigned char datafield;
    unsigned char comparisonType;
    unsigned char compareValue;
unsigned char *filename;
unsigned char active;

unsigned short xSize;
unsigned short ySize;
unsigned short xStart;
unsigned short yStart;

struct image_element *next;
}screen_image_element;

在代码中,我使用malloc:

分配struct及其文件名指针
screen_image_element *tempElement; 
tempElement = (screen_image_element *) malloc(sizeof(screen_image_element));

char *tmp;
tmp = (char *) malloc(somevalue); //somevalue is known
// fill tmp with a string
(*tempElement).filename = tmp;

在分配和使用所有内容之后(注意:此功能都像魅力一样)我想释放所有数据字段并重新开始:

void deleteMenu()
{

    screen_image_element *temp;

    while (image_elements) //image elements is the first struct in the linked list at this point
    {
        temp = image_elements->next; //save the next pointer
        free(image_elements->filename); // free the data behind the filename pointer
        free(image_elements); //free the rest of the struct
        image_elements = temp; // put the next struct as first and loop
    }
}

我无法测试这个功能,因为我知道并且无法看到当前的内存使用量,因此不提供任何返回值。 直到这一点,pic仍在运行。但是当我再次尝试分配内存时,pic崩溃了(异常处理程序调用了原因0x07:坏指针)。问题似乎源于malloc函数调用内部:

malloc(18);

也不起作用(所以功能参数或其他东西都没有错误。)

你知道这可能是什么原因吗?

0 个答案:

没有答案