一份代码可以知道具体方式和原理:
int main() { int stack_a; int stack_b; static int static_c; static int static_d; int *heap_e; int *heap_f; heap_e = (int *)malloc(10); heap_f = (int *)malloc(10); printf("The a address is %p\n",&stack_a); printf("The b address is %p\n",&stack_b); printf("The c address is %p\n",&static_c); printf("The d address is %p\n",&static_d); printf("The e address is %p\n",heap_e); printf("The f address is %p\n",heap_f); return 0; }
输出log
root@ubuntu:/home/watson/test# ./a.out The a address is 0x7ffd2d5894f0 The b address is 0x7ffd2d5894f4 The c address is 0x60104c The d address is 0x601050 The e address is 0x23db010 The f address is 0x23db030
分析:
1. ab都是堆栈中的栈内存申请,因int占用四个字节,故f0 -> f4。
2. cd都是静态存储变量申请内存,在编译时已经申请分配好,不释放。
3. ef都是动态申请内存,属于堆栈的堆内存申请,此处返回一个指针。
情况1
heap_e = (int *)malloc(20); heap_f = (int *)malloc(20);
malloc (10) -> 10bytes内存申请The e address is 0xc04010
The f address is 0xc04030
|--------------------|.....|--------------------|0xc040100xc04030中间0x20 = 32bytes,由于字节对齐,申请时需要申请20bytes,系统对malloc管理是让其在32bytes后再开辟新的内存空间。
情况2
heap_e = (int *)malloc(30); heap_f = (int *)malloc(30);
malloc (10) -> 10bytes内存申请The e address is 0xc04010
The f address is 0xc04040
|------------------------------|.....|------------------------------|0xc040100xc04040中间0x30 = 48bytes,由于字节对齐,申请时需要申请30bytes,系统对malloc管理是让其在48bytes后再开辟新的内存空间。
修改如下的程序:
printf("The e address is %p\n",heap_e); printf("The e+1 address is %p\n",heap_e + 1); printf("The f address is %p\n",heap_f); printf("The f-1 address is %p\n",heap_f - 1);
The e address is 0x12fa010
The e+1 address is 0x12fa014
The f address is 0x12fa030
The f-1 address is 0x12fa02c
0x12fa014
0x12fa02c
前后内存地址不一致,malloc多次内存是不会连续的。
Life is mess, don't let mess mess us.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库