I'm working on a project involving a PIC32MX220f032b in which i have to use dynamic memory allocation to declare an unknown number of structs in a linked list.
The malloc calls and everything worked fine, until i went on implementing the removal of the data. The idea is to allocate a number of structs and fill them with data (some via pointers). At a point in time, all known structs are freed an new ones are declared.
The first test with only allocation worked for about three rounds until it ran out of memory (understandable). But when i implement a function to free the data structures, malloc is no longer functioning. It's function call crashes the pic and sends it to its exception handler with a pointer error. But i cannot figure out why...
I use the following struct:
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;
In the code, i allocate the struct and it's filename pointer with malloc:
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;
After everything is allocated and used (note: this functionality all works like a charm) i want to free all data fields and start over:
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
}
}
I cannot test the functionality of this as free doesn't provide any return values as far as i know and a cannot see the current memory usage. Until this point the pic still runs. But when i try to allocate memory again the pic crashes (exception handler called with cause 0x07: bad pointer). The problem seems to originate from inside the malloc function call as:
malloc(18);
doesn't work as well (so no fault in function parameters or something).
Do you have any idea what could be the cause of this?