程序中堆和栈增长方向以及大小端问题

来源:互联网 发布:node文档 编辑:程序博客网 时间:2024/06/06 14:01

借鉴:

http://midautumn.bokee.com/7005452.html

http://www.cnblogs.com/xkfz007/archive/2012/06/22/2558935.html


对于栈的增长方向,由于c++中局部变量与函数参数的地址与编译器有一定依赖关系,在此通过函数调用函数,从而确保比较地址不依赖编译器。

对于堆的话,直接分配在比较地址即可,最后记得释放堆资源。

大小端:小端的话是低位存在地址,大端是低位存在高地址。俩者相反。


#include <iostream>using namespace std;//栈的判定bool up(false);void find_stack_direction(){static char *addr = NULL;char temp;if(addr == NULL){addr = &temp; find_stack_direction();}else{up = addr > &temp ? false:true;//addr为上一层函数的地址值}}//堆的判定bool if_heap_up(){int *first = new int;int *second = new int;bool result(false);result = second > first? true:false;delete first;delete second;return result;}//大小端bool is_big_endian(){short x(1);return *((char*)&x) != 1;}int  main(void){//栈find_stack_direction();if (up){cout<<"栈为高地址增长!"<<endl;}else{cout<<"栈为低地址增长!"<<endl;}//堆if (if_heap_up()){cout<<"堆为高地址增长!"<<endl;}else{cout<<"堆为低地址增长!"<<endl;}//大小端if(is_big_endian()){cout<<"大端!"<<endl;}else{    cout<<"小端!"<<endl;} return 1;}
结果如下:

栈为低地址增长!
堆为高地址增长!
小端!

//按正常可知,栈是从高地址向低地址方向,堆从低地址向高地址方向。俩者刚好都往中间分配。

0 0
原创粉丝点击