How to fill RAM in unix

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

For a laugh I wanted to overload my system from bash. I found the following snippet online:

function malloc() {
  if [[ $# -eq 0 || $1 -eq '-h' || $1 -lt 0 ]] ; then
    echo -e "usage: malloc N\n\nAllocate N mb, wait, then release it."
  else
    N=$(free -m | grep Mem: | awk '{print int($2/10)}')
    if [[ $N -gt $1 ]] ;then
      N=$1
    fi
    sh -c "MEMBLOB=\$(dd if=/dev/urandom bs=1MB count=$N) ; sleep 1"
  fi
}

How does this work?

The first two lines of the function look at the arguments given. Help is echoed to the user if:

The rest of the code involves the use of the free command as well as the dd command.

Together this reads 1mb times the function input ($1) worth of noise and assigns it to a constant MEMBLOB in a subshell that lasts 1 second, then relinquishes it. But before the memory is relinquished, the RAM usage increases.

Resources