一份代码可以知道具体方式和原理:

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
|--------------------|.....|--------------------|
0xc04010
            0xc04030
中间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
|------------------------------|.....|------------------------------|
0xc04010
                      0xc04040
中间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多次内存是不会连续的。



最新文章

  1. Outfit7 庆祝其开发工作大获丰收
  2. PAT (Advanced Level) Practise:1008. Elevator
  3. python 函数可变长参数
  4. Bootstrap 框架 栅格布局系统设计原理
  5. iOS- SQLite3的基本使用
  6. EntityFramework Add方法与Attach区别
  7. 【noip模拟】考试总结
  8. hadoo namenode format 异常 java.net.UnknownHostException: localhost.localdomain: localhost.localdomain
  9. 自制单片机之十八……无线通讯模块NRF24L01+
  10. openlayers二:添加矢量图形文字
  11. (八)jdk8学习心得之Optional类
  12. java 判断语句和循环语句
  13. TCP 的那些事儿
  14. Windows 循环根据进程名称 存在则删除该进程
  15. python实现邮件接口——smtplib模块
  16. 解决虚拟机vmware虚拟机安装64位系统“此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态”的问题
  17. Error:Error converting bytecode to dex: Cause: com.android.dex.DexException: Multiple dex files define Lcom/lidroid/xutils/task/TaskHandler;
  18. C++,坑...
  19. C++ 函数 内联函数
  20. hdu 3397 线段树

热门文章

  1. HTML5知识点笔记
  2. 《操作系统导论》第14章 | 内存操作API
  3. .Net Core AOP之IExceptionFilter
  4. 【整理】Linux:set -eux
  5. Burp intruder暴力攻击web口令
  6. Java8新特性系列-默认方法
  7. 安装python和pycharm,以及常见安装问题
  8. 【C#表达式树 六】表达式树中创建节点的两种方式
  9. C# 方法里面的默认参数
  10. csv 转换为DBF文件的方法