Not Enough Memory? Extend Memory with Swap

You get Not Enough Memory while running a command? How can you fix it? The obvious solution is increase the amount of memory installed in the machine. There is another approach to tackle the problem. In this tutorial, we will see how to extend the memory via swap file.

Reproduce 'Not enough memory' Error

To reproduce the error, we will create a simple python script which invoked with the number of MB to allocate. If the script success to allocate the requested amount of memory – it will print success => nMB was allocated, otherwise failure => nMB can not be allocated will be printed.

Creating memory-test.py

create memory-test.py in your favorite editor and enter the following content:

memory-test.py
 #! /usr/bin/python
 import ctypes
 import sys

 size = int(sys.argv[1])
 class MemoryTest(ctypes.Structure):
     _fields_ = [  ('chars' , ctypes.c_char*size * 1024*1024 ) ]

 try:
     test = MemoryTest()
     print('success => {0:>4}MB was allocated'.format(size) )
 except:
     print('failure => {0:>4}MB can not be allocated'.format(size) )

Now, make the script executable:

Update permissions
 main@work:~# chmod 755 memory-test.py

Invoking memory-test.py

Now , let's use this script with growing number of MB until a failure is reported:

Find maximum allocation space size
 main@work:~# ./memory-test.py 10
 success =>   10MB was allocated
 main@work:~# ./memory-test.py 295
 success =>  295MB was allocated
 main@work:~# ./memory-test.py 310
 failure =>  310MB can not be allocated

To see the reason why the script failed at 310MB we run free -m which displays the amount of free and used memory in the system in MB:

free command - Find available memory
 main@work:~# sudo free -m
             total        used        free      shared  buff/cache   available
 Mem:          488         148         140           9         199         302

We can see, there is swap memory. Let's fix it