background image

… …

… …

代码区
静态数据区

低端内存区域
高端内存区域
… …

常量存储区

… …
iLocalInt2 = 0x0012ff3c

iLocalInt3 = 0x0012ff40

RET
iFuncParam2 = 0x0012ff4c

低端内存区域
高端内存区域
… …

iFuncParam1 = 0x0012ff48
iFuncParam3 = 0x0012ff50
iLocalInt1 = 0x0012ff38

C 语言内存管理

对于一个 c/c++程序员来说,内存泄漏是一个常见的也是令人头疼的问题,为了应对这个

问题,有许多技术被研究出来来解决这个问题,例如 Smart Pointer,Garbage Collection 等。一

般我们常说的内存泄漏是指堆内存的泄漏。那么为什么会导致内存泄漏呢?通过学习内存管

理,相信你一定能解决好这个问题。

1. C 语言内存管理方式

在进入本专题前,我们先看一下下面的程序,来简单分析以下 C 语言的内存管理:

#include <stdio.h> 
#include <malloc.h>

//全局变量定义
int iGlobalInt1=0;

int iGlobalInt2=0;
int iGlobalInt3=0;

//全局常量定义
const int iGlobalConstInt1=1;

const int iGlobalConstInt2=5;
const int iGlobalConstInt3=6;

//全局静态变量定义
static int iGlobalStaticInt1=0;

static int iGlobalStaticInt2=0;
static int iGlobalStaticInt3=0;

//函数定义
void  funcParamTest(int iFuncParam1,int iFuncParam2,int iFuncParam3) 


    //函数私有变量定义
    int    iLocalInt1=iFuncParam1;

int    iLocalInt2=iFuncParam2;
int    iLocalInt3=iFuncParam3;

printf("函数参数变量内存地址\n");

printf("iFuncParam1=0x%08x\n",&iFuncParam1);
printf("iFuncParam2=0x%08x\n",&iFuncParam2); 

printf("iFuncParam3=0x%08x\n\n",&iFuncParam3); 

printf("函数本地变量的内存地址\n");
printf("iLocalInt1=0x%08x\n",&iLocalInt1); 

printf("iLocalInt2=0x%08x\n",&iLocalInt2); 
printf("iLocalInt3=0x%08x\n\n",&iLocalInt3); 

return; 

//入口函数
int main(int argc, char* argv[])