Bill Knight wrote: > Quintin Beukes wrote: >> On Tue, Oct 6, 2009 at 5:39 PM, Olin Lathrop wrote: >>> Another drawback of dynamic memory on a small system is how to >>> guarantee you won't run out. If you don't know how much memory you >>> need up front, then how do you know you don't need more than there >>> is available under the right set of input conditions. And if you >>> do use malloc or the like, what are you going to do when it fails? >>> Punting back to the operating system with a non-zero exit status >>> doesn't work here. >> >> Though so far I've not been able to come up with a solution for a >> specific problem where the mode of the device can change and so the >> data it stores changes. Though both structures sometimes need >> memory, depending on it's status. We basically solved it by >> overlaying the same structure over a memory block and giving it an >> ID to know what to cast to, though 2 dynamically sized linked lists >> would have been the ideal solution here. > > One of the problems with malloc & free is memory fragmentation due to > the variable size of the blocks that are allocated and released. > Another approach that is often used in embedded systems is a memory > pool of fixed sized blocks where the size of the blocks in a given > pool is large enough to hold all of a specific item item. If an item > is somewhat smaller than a block, it just doesn't use all of it. The > result is still much safer. If you need both big and small blocks > then have the small block manager get a big block from the big block > allocator and divide it into small fixed size blocks. If it needs > more small blocks, have it get another big block and divide it. Another approach could be a union of two arrays with different member types. No list => no dynamic allocation needed. Array => can be used as circular buffer or stack. Overall union (as opposed to individual union) => all the available space is used (in case the types have sufficiently different sizes that this makes a difference). One of the main issues here is that dynamic memory is not predictable. Usually you need to make sure that in the worst case scenario (per spec) the available memory is enough (queue length, etc.) With dynamic memory, you don't even know before-hand how much usable memory you have, due to fragmentation. Only a 'designed' memory solution can give you that. With this in mind, malloc et al is generally out of the picture anyway. Gerhard -- http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist