STL内存管理之char[1]

来源:互联网 发布:java web树形菜单例子 编辑:程序博客网 时间:2024/05/21 09:15

union obj

{union obj* free_list_link;char client_data[1];};

       以前看《STL源码剖析》的时候,在空间配置器章节的时候遇到过这段代码,对其中的char client_data[1]一直不明就里。现在才知道这是C语言的一个小trick,将struct的最后一个成员变量定义为char[1],可以动态的扩充struct的容量(对union亦然),这一特点常用在内存池的构建中。

       之所以使用char[1]而不用char*的原因主要有两点:

       1.char data[1]的大小为1字节,而char*在32位系统上为4个字节,在32位系统上运行下面代码可以发现前者的大小为5个字节,后者为8字节(__attribute((packed))指示编译器取消对齐优化)。

#include <iostream>using namespace std;struct obj_a{obj_a *next;char  data[1];}__attribute((packed));struct obj_p{obj_p *next;char  *data;}__attribute((packed));int main(){cout<<sizeof(obj_a)<<endl;cout<<sizeof(obj_p)<<endl;return 0;}

        2.使用char*需要显式的为指针分配内存和销毁,而使用char[1]则无此顾及。  ps:多数情况下使用char[0],因为这样更节省空间,但是有些编译器不支持char[0],所以使用char[1]兼容性更好。

#include <iostream>#include <cstdlib>using namespace std;#define EXTRA 5struct obj_a{obj_a *next;char  data[1];}__attribute((packed));struct obj_p{obj_p *next;char  *data;}__attribute((packed));int main(){obj_a *t1 = (obj_a*)malloc(sizeof(obj_a) + EXTRA * sizeof(char));for(int i = 0; i < EXTRA; i++){(*t1).data[i] = 'a' + i;cout<<(*t1).data[i]<<" ";}cout<<endl;free(t1);obj_p *t2 = (obj_p*)malloc(sizeof(obj_p));(*t2).data = (char*)malloc(EXTRA * sizeof(char));for(int i = 0; i < EXTRA; i++){(*t2).data[i] = 'A' + i;cout<<(*t2).data[i]<<" ";}cout<<endl;free((*t2).data);free(t2);return 0;}
原创粉丝点击