As a preface, I am aware that it is generally bad practice to use dynamic memory allocation in embedded code. On the other hand, there are certain things you 100% need it for, and if used sparingly, it can be useful.
For those of you who want dynamic memory allocation on your program, I wrote an allocator, which can be used similarly to malloc/free. It reserves a total of 1024 bytes, within which it can dynamically allocate memory for you. You can increase or decrease this amount with some minor tweaks.
Every allocation you perform has an overhead of 4 bytes, e.x., if you allocate a ten byte structure, 14 bytes of memory are used. An allocation requires time linearly proportional to the number of currently allocated blocks, and deallocation takes place in roughly constant time. For real world use, the amount of time taken in either situation is negligible, and might even be usable within an ISR (although I have not tried it). Freed blocks which can be recombined are automatically recombined to prevent fragmentation.
It provides two functions:
Code:
/* Include ElevenAlloc.h to access these functions. */
void *elevenAlloc(unsigned int amount);
void elevenDealloc(void* memPtr);
/* For example, to allocate ten ints, you could do */
int *myArray = elevenAlloc(sizeof(int) * 10);
/* Make sure you free them later to prevent memory leaks */
elevenDealloc(myArray);
Just add ElevenAlloc.h and ElevenAlloc.c to your project to revolutionize your life. The code is licensed under the BSD license, so you can use it within your project for free, but you may not remove the copyright notice.