Linux Tips guides, explanations and reader checklists on whilenetworking.com

Troubleshooting High Memory Usage: Identifying Leaks with ‘pmap’ and ‘smem’

High memory usage is one of the most common symptoms of a Linux system under stress. When RAM fills up, performance degrades, services may crash…

High memory usage is one of the most common symptoms of a Linux system under stress. When RAM fills up, performance degrades, services may crash unexpectedly, and users experience lag or timeouts. While tools like free -h tell you how much memory is used, they rarely explain why. To move from observation to remediation, you must identify the specific processes consuming resources and analyze their internal memory maps. This guide focuses on two powerful command-line utilities: pmap and smem. These tools allow you to dissect a process’s memory footprint, distinguishing between code, shared libraries, private data, and potential leaks.

Understanding the Memory Landscape

Before diving into specific commands, it is essential to understand what you are looking at. Linux processes manage memory in several regions:
* Code (Text): The executable instructions of the program. This is usually read-only and does not grow during execution.
* Data (Heap/Stack): Dynamic memory allocated by the application. This is where leaks most frequently occur.
* Shared Libraries: Code loaded once but mapped into multiple processes (e.g., libc.so).
* Private vs. Shared: Memory can be shared between processes (efficient) or private to a single process (used for heap/stack).

When a process consumes gigabytes of memory, the goal is to determine if that memory belongs to the “Private” category and is growing uncontrollably. The pmap command provides a detailed breakdown of these regions, while smem (often found in the sysstat package) offers a cleaner, aggregated view suitable for identifying the top offenders across the entire system.

Prerequisites and Environment Setup

To perform these analyses effectively, you need root or sudo privileges for certain commands, particularly when viewing other users’ processes or exporting memory maps to files. Additionally, having a recent version of GNU coreutils and the sysstat package installed is recommended.

On most distributions, you can install smem via your package manager:

# For Debian/Ubuntu
sudo apt-get update
sudo apt-get install sysstat smem

# For RHEL/CentOS/Fedora
sudo dnf install sysstat smem

Note: If smem is unavailable, the standard pmap utility included with GNU coreutils or procps-ng serves as a robust alternative.

Step-by-Step Analysis Using pmap

The pmap command reads the /proc/[pid]/maps file to generate a memory map. The syntax is straightforward: pmap [PID]. To get a human-readable output with sizes in kilobytes, use the -x flag.

Run the following command against a specific process ID (PID) suspected of high usage:

sudo pmap -x <PID> > memory_map_<PID>.txt

For example:

sudo pmap -x 12345 > memory_map_12345.txt

Interpreting the Output

When you open the resulting file, look for the “anon” (anonymous) and “shared” columns. Anonymous memory is not backed by a file on disk; it represents heap or stack allocations. If you see a large number of lines with significant sizes in the anon column, the process is likely allocating memory dynamically.

Illustrative Output Analysis:

    PID   PPID  USER       STAT   VSZ  RSS  PMAP
   12345     1  root      S      800M 750M
...
Address         Kbytes     Mode  RefCnt  Shared  Anonymous
0040000000-0040020000 rw-p     0       0        3145728

In this example, the Anonymous column shows ~3GB. If this number is increasing over time while the process remains stable in CPU usage, it strongly indicates a memory leak where the application allocates memory but fails to release it.

Aggregating Data with smem

While pmap is excellent for deep-diving into a single process, smem excels at system-wide aggregation. It simplifies the complex /proc/[pid]/maps output into a readable table sorted by Resident Set Size (RSS).

To find the top memory consumers on your server:

smem -r -k | sort -n -k 2 | head -n 10 > top_consumers.txt

This command sorts processes by RSS in kilobytes and lists the top 10. The output typically includes the PID, user, command name, and memory usage. This is crucial for quickly identifying if a known application (like java or nginx) is behaving abnormally compared to its baseline.

Verification and Common Pitfalls

A frequent mistake when troubleshooting memory issues is confusing Virtual Memory (VSZ) with Resident Set Size (RSS). VSZ includes all memory the process has ever touched, including swapped-out pages and shared libraries. RSS represents the physical RAM currently in use. Always analyze RSS for leak detection.

Another common error is misinterpreting shared library growth. If a process uses pmap and shows increasing usage in the “shared” column, it may simply mean that many other processes are now running that same library, not that the current process leaked memory. Focus your analysis on the “anon” or “private” sections.

Verification Steps:
1. Monitor Over Time: Run pmap or smem twice with a 5-minute interval. If the RSS value in the anonymous region increases significantly between runs, a leak is confirmed.
2. Check Swap Usage: Correlate high RSS with swap usage using swapon --show or free -h. High RSS combined with active swapping indicates the system is struggling to manage memory pressure.
3. Review Application Logs: If pmap confirms a leak, check application logs for error messages related to allocation failures (e.g., “out of memory” errors in Java heap dumps or Node.js heap snapshots).

Student Practice Task: The Leaking Daemon

To solidify your understanding, try this exercise in a safe lab environment (like a virtual machine):
1. Start a simple loop script that allocates memory repeatedly without releasing it:
bash
while true; do
val=$(python3 -c "import sys; print('a'*100000)")
done &

2. Note the PID of this background process.
3. Run pmap -x <PID> every minute for five minutes.
4. Observe how the anon column grows linearly while the command continues running.
5. Finally, kill the process and observe the memory being reclaimed by the kernel.

Industry Application: Production Incident Response

In a production environment, you cannot afford to guess. When an alert fires for high memory usage on a web server:
1. Identify the noisy neighbor using smem -r.
2. If a specific application (e.g., a custom Python script) is flagged, use pmap to verify if it is holding private memory.
3. If confirmed as a leak, do not immediately restart the service without logging the evidence. Restarting masks the symptom and makes root cause analysis harder later.
4. Work with the application team to patch the code or increase limits if appropriate.

Remember that terms, availability, eligibility, laws, and prices depend on insurer, policy and jurisdiction regarding liability for downtime caused by resource leaks. Always verify policy terms with authoritative sources before making claims about SLA breaches. Similarly, technology content must give safe, non-destructive instructions; identify OS/software-version differences and explain security considerations when analyzing memory maps to ensure you do not inadvertently expose sensitive data in /proc files if permissions are misconfigured.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.