這兩天線上的一個服務出現了內存問題,表如今使用top查看進程的RES會間斷性的忽然上升,並且從不降低。仔細review了線上的代碼,沒有發現內存泄漏,懷疑和glibc的內存分配機制有關,glibc並無及時將內存釋放給操做系統。html
能夠自行使用以下的測試代碼進行下驗證,會發現使用默認的glibc和google提供的tc_malloc,map吃掉的內存在離開本身的scope後並無吐給操做系統,使用jemalloc沒有如上問題。線上的代碼已經從新用jemalloc編譯推進上線了,還處在觀察階段。linux
#include <malloc.h> #include <map> #include <iostream> #include <stdlib.h> //#include "google/malloc_extension.h" void testmap() { std::cout << "*************1 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; std::map<int, int> testmap; for(int i = 0; i != 10000000; i++) { testmap[i] = i; } std::cout << "*************2 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; testmap.clear(); std::cout << "*************3 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; } int main() { //static const int DEFAULT_MMAP_THRESHOLD = 0; //::mallopt(M_MMAP_THRESHOLD, DEFAULT_MMAP_THRESHOLD); testmap(); //MallocExtension::instance()->ReleaseFreeMemory(); sleep(20); std::cout << "*************4 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; }
以下,記錄下在網上查到的一些資料:ios
jemalloc程序員
更好的內存管理-jemalloc (^_^給程序員最後的免費的午飯)緩存
tcmallocnosql
TCMalloc : Thread-Caching Mallocsvn
glibc
glibc內存管理ptmalloc2源代碼分析 (大殺器,慎入,一份130頁的pdf文檔)
STL
實際應用
Will malloc implementations return free-ed memory back to the system?
from:http://www.cnblogs.com/liuhao/archive/2013/04/24/3040125.html
=========================================
http://www.2cto.com/os/201212/180499.html(Linux的進程與內存管理)