How to Fix 'Cannot Allocate Memory' Error in Linux
cannot allocate memory error in Linux happens when the system runs out of available RAM or swap space. To fix it, free up memory by closing programs, increase swap space, or adjust memory limits using ulimit or system settings.Why This Happens
This error occurs because Linux cannot find enough free memory to complete a task. It happens when your programs or processes request more memory than what is available in RAM and swap combined. For example, running a program that tries to allocate a very large array without enough free memory triggers this error.
# Broken example: Trying to allocate a huge array in a C program #include <stdlib.h> #include <stdio.h> int main() { size_t size = 1024UL * 1024UL * 1024UL * 10UL; // 10 GB char *buffer = malloc(size); if (!buffer) { perror("malloc"); return 1; } printf("Memory allocated successfully\n"); free(buffer); return 0; }
The Fix
To fix this error, reduce the memory your program requests or increase available memory. You can add swap space to give Linux more virtual memory or close other programs to free RAM. Also, check and increase user memory limits with ulimit. Here is a corrected example that allocates less memory safely.
# Fixed example: Allocate smaller memory block #include <stdlib.h> #include <stdio.h> int main() { size_t size = 1024UL * 1024UL * 100UL; // 100 MB char *buffer = malloc(size); if (!buffer) { perror("malloc"); return 1; } printf("Memory allocated successfully\n"); free(buffer); return 0; }
Prevention
To avoid this error in the future, monitor your system memory usage regularly using commands like free -h or top. Add swap space if your workload needs more memory than physical RAM. Set appropriate memory limits with ulimit -v to prevent runaway processes. Also, optimize your programs to use memory efficiently and handle allocation failures gracefully.
Related Errors
Similar errors include Out of memory: Kill process when the Linux kernel kills processes to free memory, and Cannot allocate stack when stack size limits are too low. These can be fixed by adjusting kernel parameters, increasing limits, or optimizing memory use.