How to defragment memory?

Following the topic raised by Tazling "Is String function family inherently dangerous?" where it has often mentioned that "String can/will cause memory fragmentation", it got me thinking and I wondered if there is anyway or code to De-fragment uC memory like you could execute on on a PC...any ideas?

I doubt it. There's nothing keeping track of references to objects, so if a defragment routine tried to move one, all your pointers/references to heap items would be invalid, likely leading to some unexpected behaviour.

You could fix fragmentation by resetting the microcontroller but that's just clearing the memory, not defragmenting it.

Even if it was possible, you would not like it. As I recall, the old Basic programs and perhaps Pascal did what you want, but in both cases, your program just STOPPED while the defragmenting happened.

Paul

sherzaad:
Following the topic raised by Tazling "Is String function family inherently dangerous?" where it has often mentioned that "String can/will cause memory fragmentation", it got me thinking and I wondered if there is anyway or code to De-fragment uC memory like you could execute on on a PC...any ideas?

When free() is called, it DOES "de-fragment", to the extent possible. This means the free'd block will be combined with adjacent free blocks. Without a pretty fine-grained hardware Memory Management Unit, that is ALL that can be done, without adding a completely ridiculous amount of overhead to ALL memory allocation/de-allocation operations, and a significant amount of RAM overhead. Both of those would seriously impact performance, and reduce usable memory, which kinda defeats the whole purpose.
Regards,
Ray L.