Identify Heap Leaks
Learn how to identify heap leaks.
The application App9
was found to consume more and more memory. There were several core memory dumps that were saved at different times with corresponding pmap
logs. In this exercise, we’ll try to identify the cause of this memory leak.
Application source code
For reference, here’s the code of this application:
Press + to interact
// Build:// gcc main.c -pthread -static -o App9#include <stdio.h>#include <pthread.h>#include <unistd.h>#include <string.h>#include <stdlib.h>void procD(){}typedef void (**PFUNC)();void procC(int iter){for (int i = 0; i < iter; ++i){char *p = malloc(256);strcpy(p, "allocated memory");*(PFUNC)(p + 32) = &procD;}}void procB(){procC(250000);sleep(300);procC(250000);sleep(-1);}void procA(){procC(5000);sleep(300);procB();}#define THREAD_DECLARE(num, func) \void bar_##num() \{ \func; \} \\void foo_##num() \{ \bar_##num(); \} \\void *thread_##num(void *arg) \{ \foo_##num(); \return 0; \}THREAD_DECLARE(one, sleep(-1))THREAD_DECLARE(two, procA())THREAD_DECLARE(three, sleep(-1))THREAD_DECLARE(four, sleep(-1))THREAD_DECLARE(five, sleep(-1))#define THREAD_CREATE(num) \{ \pthread_t threadID_##num; \pthread_create(&threadID_##num, NULL, thread_##num, NULL); \}int main(int argc, const char *argv[]){THREAD_CREATE(one)THREAD_CREATE(two)THREAD_CREATE(three)THREAD_CREATE(four)THREAD_CREATE(five)sleep(-1);return 0;}
Loading the first core dump
We’ll start with loading the core dump App9.core.2.230
:
gdb -c App9.core.2.230 -se App9
The above command will output the following to the terminal:
Press + to interact
Identifying the
...Access this course and 1400+ top-rated courses and projects.