Today, I re-read "STL source code analysis", so I can't help but admire the classic design of STL. The STL space adaptation code design is particularly incisive, not only considering the hidden danger of memory fragmentation, but also considering the thrift and reuse of the pointer space, reducing the extra burden of maintaining the lists. Let's take a look at the following code;
First look at the STL struct,
union obj{ union obj *free_list_link; char clent_data[1]; /* the client sees this */};
Since OBJ uses union, OBJ can be regarded as a pointer pointing to another OBJ in the same form from its first field. From the second field, OBJ can be regarded as a pointer pointing to the actual region. The result is that the memory fee will not be incurred in order to maintain the pointer required by the linked list.
Take a look at the following sample code, and you will find that its design is exquisite!
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<iostream>using namespace std;union obj{ union obj *free_list_link; char clent_data[1]; /* the client sees this */};int main(){ obj *op1 = (obj *)malloc(32); strcpy(op1->clent_data,"hello free!"); obj *op2 = (obj *)malloc(32); op2->free_list_link = NULL; obj *op3 = (obj *)malloc(32); strcpy(op3->clent_data,"hello free l"); printf("----------------------------------------\r\n"); printf("address freelist:%ld\r\n",(long)(op3->free_list_link)); printf("address clentdata:%ld\r\n",(long)&(op3->clent_data)); obj *op4 = (obj *)malloc(32); op4->free_list_link = op2; obj *op5 = (obj *)malloc(32); op5->free_list_link = op4; printf("----------------------------------------\r\n"); obj *begin = op5; while(begin){ printf("%ld\r\n",(long)begin); begin = begin->free_list_link; } /* release op3 */ op2->free_list_link = op3; op3->free_list_link = NULL; printf("----------------------------------------\r\n"); printf("address freelist:%ld\r\n",(long)(op3->free_list_link)); printf("address clentdata:%ld\r\n",(long)&(op3->clent_data)); printf("----------------------------------------\r\n"); begin = op5; while(begin){ printf("begin:%ld\r\n",(long)begin); begin = begin->free_list_link; } return 0;}
The output is as follows:
----------------------------------------
IP address freelist: 1819043176
Address clentdata: 143143000
----------------------------------------
143143080
143143040
143142960
----------------------------------------
Address freelist: 0
Address clentdata: 143143000
----------------------------------------
Begin: 143143080
Begin: 143143040
Begin: 143142960
Begin: 143143000