Sometimes you run across a situation where you want some more memory (RAM) to complete an operation. An example of this that I ran into was trying to compile something and gcc kept running out of memory. One way to fix this is to temporarily allocate more swap space.
Swap space is memory that resides on your hard drive (or SD card in the case of a Raspberry Pi) that can be used like RAM. This is helpful if you are running into an out of memory error, as it will give the computer more places to store things. The downside is that the hard drive is much, much slower than RAM. So, if your process needs this extra memory, then it is going to run much slower. In the situation of compiling, it means that it will take longer to compile a program, but it will actually finish without an error. A reasonable trade off.
Allocating More Swap Space
Here’s the steps to allocate more swap space:
The fallocate command allocates a 1GB worth of space and assigns it to a file called /mnt/1GB.swap. The name is for our sanity so that we know exactly what the file was intended to do. The chmod command changes the permission on the file so that only root can read and write to the file. The mkswap command sets up the file to be used as swap space. Finally, the swapon command turns on swapping to the file that we created.
How much space to allocate depends on what you are trying to accomplish. If this is a temporary thing, I’d say pick a larger value than what you think you will need.
Removing the Swap Space
Once you are done with the swap space that you have allocated, you can remove it with:
This is a great way to give yourself more memory to complete a task and then free it back up when you are done.