There are two options for defragmentation. You can do it the Easy Way, or you can do it the Good Way:
Keep the data to be moved and defragmented entirely in memory. Essentially you have to read entire files until you free up enough space to then write one back in a continuous block.
- the upside to this is that it will be faster and not need extra storage on the disk
Move the data elsewhere on disk, then move it back when a continuous block large enough is created.
- this way is a lot slower as data has to be repeatedly read and written somewhere else.
Option 1 potentially does not need extra space on the disk, but is also potentially dangerous.
- While files are being read and deleted the data no longer exists on disk. In the event of a power cut whatever files have been read but not restored to their new location are lost, potentially with catastrophic effects.
- you have no idea how large a buffer you might need to read files. You might have multi gigabyte files that need moving or a lot of tiny files. It needs either the ability to allocate potentially infinite amounts of memory (expanding the page file and making fragmentation worse), or use a fixed percentage of memory. If you have a fixed buffer size you could load (and truncate) part of the file to free up space, but you end up in a worse position in that you could have missing parts of files in the event of power failure which would arguably be worse than missing the whole file.
Option 2 always guarantees that your data is on disk, especially if you copy first and then delete blocks.
So yes, for safe defragmentation without looming threat of catastrophic data loss, you need some disk space free.