这两天线上的一个服务出现了内存问题,表如今使用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的进程与内存管理)