Problem with using malloc in linked lists
I've been working on this program for five months now. Its a real time application of a sensor network. I create several linked lists during the life of the program and Im using malloc for creating a new node in the link. What happens is that the program suddenly stops or goes crazy and restarts. Im using AVR and the microcontroller is ATMEGA 1281. After a lot of debugging I figured out that that the malloc is causing the problem. I do not free the memory after exiting the function that creates a new link so Im guessing that this is开发者_如何学运维 eventually causing the heap memory to overflow or something like that. Now if I use the free() function to deallocate the memory at the end of the function using malloc, the program just gets stuck when the control reaches free(). Is this because the memory becomes too clustered after calling free() ?
I also create reference tables for example if 'head' is a new link list and I create another list called current and make it equal to head.
table *head;
table *current = head;
After the end of the function if I use free
free(current);
current = NULL:
Then the program gets stuck here.
I dont know what to do. What am I doing wrong? Is there a way to increase the size of the heap memory?
Whether you need to free a block at the end of the function calling malloc() should be determined by whether the memory block is still used after the call. If it is becoming a node in the list then you should not free it at the end of the function. If it is used for temporary working memory during the call then you must free it at the end or you will eventually exhaust your heap. You must free the block when it is removed from the list.
In any case using malloc() and free() on small memory blocks (i.e. linked list operations) in a real-time system (no virtual memory) is going to lead to eventual heap fragmentation.
What you need to do is use a pool of memory blocks and recycle the buffers. Are you running an RTOS or is this bare metal? There are existing memory pool libraries available if you look. You can also write one but it is relatively easy to create something worse than no library at all unless you're really experienced in this area.
Provide more details if you need more specific advice.
精彩评论