The following error indicates that dd can not allocate 8GB ram
fatal error: runtime: out of memory
dd: out of memory
Your free command shows you only have 2011MB free memory. Linux and Unix like oses do aggressive caching[1]. You can flush disk caching using the following command:
echo 3 | sudo tee /proc/sys/vm/drop_caches
Verify it:
free -m
Fixing dd: out of memory
But, this will not solve your problem as you have 8GB max ram. To fix this simply lower dd bs=NN value. For instance try using 1GB x 8 count as follows:
sudo dd if=/dev/zero of=/swap-file count=8 bs=1GB
Where,
if=/dev/zero : Read from /dev/zero
of=/swap-file : Write to /swap-file
count=8 : Copy only N input blocks
bs=1GB : Read and write 1GB bytes at a time
In short, you must specify bs count less than available memory and multiply with count to get the desired result.
[1] https://www.linuxatemyram.com/
That did it. I am so stupid and should have thought about max ram. That is the difference between trained Linux sysadmin and developer. Thank you once again.