Do you mean defrag by moving allocated memory around to make larger chunks of free memory? Or do you just mean consolidation, where two chunks of free memory that are consecutive are replaced with one chunk of free memory that spans the two?
Because you have to worry about what Pype said if you're talking about moving around allocated memory. Otherwise, you should be able to write a relatively simple, straightforward algorithm that checks when an allocation is freed if there is a free one immediately after it. Checking before it becomes more difficult since you dont know how long it would be, but I'm sure you can find something online about this. Look up something like "memory allocation algorithms" on google and you should get lots of info.
Unfortunately, my mem man. right now is far from optimized, and that's something I have on my list to look into. So if you find out anything really good, leave a note here...