Finding and fixing memoy leaks in your software

Memory leaks will cause your device to crash after a period of time once it runs out of memory.
A quick way to find out if your application has memory leak(s) is too monitor it with top:

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
1       root       15   0   2156    668  572 S     0           5 .0      0:00.14         application

Not the way to fix a leak...

Not the way to fix a leak…

If you see the %MEM increase over time for no particular reasons, then you’ve got a memory leak.

However, it might be tricky to isolate where the issue occurs exactly.

The first thing to do is the review your source code for the following:

  1. Malloced memory is always freed
  2. fopen is always followed by fclose, and open by close
  3. scandir calls are properly freed
  4. Threads are properly terminated with pthread_cancel & pthread_join or pthread_detach, etc…

If after a code review you cannot find the reason for the memory leak, use the following piece of code:

int return_process_memory_usage(void)

{
char buf[64];
int fd = open(“/proc/self/statm”, O_RDONLY);

if(fd < 0) {
return -1;
}

read(fd, buf, sizeof(buf));
close(fd);
return atoi(buf);
}

#define DISPLAY_MEMORY_USAGE             fprintf(stderr, “Memory usage: %d pagesn”, return_process_memory_usage);

The memory usage is displayed in number of pages. Usually one page is 4096 bytes but it obviously depends on your system.

After you added this debug code,  insert the macro DISPLAY_MEMORY_USAGE at strategic places in your code (e.g. before a thread starts and after it stops) to find out where the memory leak occurs.  Then run the code and check the log to locate the issue.

Once your located where the memory leak occurred, narrow down your search by adding more DISPLAY_MEMORY_USAGE in your code and remove the unused ones until you finally pinpoint the exact place in your code and resolve the issue.

Tweet Memory leaks will cause your device to crash after a period of time once it runs out of memory. A quick way to find out if your application has…

Leave a Reply

Your email address will not be published. Required fields are marked *

*