2008年8月5日 星期二

有趣的union 結構

當THREAD_SIZE 取32,struct thread_info a再隨意加成員資料,則 union thread_union b 中的stack 任意元素 位置 (ex: &b.stack[1])與 ~(THREAD_SIZE-1)取and會得到 union thread_union b中的 thread_info位置。

#include

#define THREAD_SIZE (32)


struct thread_info{
unsigned long t;
int a;
char flags1[56];
unsigned c;
char d;
unsigned n;
char flags2[128];
} a;
union thread_union {
struct thread_info thread_info;
unsigned long stack[THREAD_SIZE/sizeof(long)];
} b;


int main(){
void *p1;
void *p2;
unsigned long esp;

printf("sizeof (thread_info)=%d\n",sizeof(struct thread_info));
printf("THREAD_SIZE=%d\n", THREAD_SIZE);
printf("~(THREAD_SIZE-1)=%x\n",~(THREAD_SIZE-1));
printf("thread_info address=%x \n",&b.thread_info);
printf("statck address=%x \n",b.stack);
printf("statck [0] address=%x \n",&b.stack[0]);
printf("statck [1] address=%x \n",&b.stack[1]);

p1=&b.stack[0];
esp=(unsigned long)p1;
p2=(struct thread_info *)(esp & ~(THREAD_SIZE-1));
printf("address=%x \n",p2);

p1=&b.stack[1];
esp=(unsigned long)p1;
p2=(struct thread_info *)(esp & ~(THREAD_SIZE-1));
printf("address=%x \n",p2);
}

Output:

sizeof (thread_info)=204
THREAD_SIZE=32
~(THREAD_SIZE-1)=ffffffe0
thread_info address=8049940
statck address=8049940
statck [0] address=8049940
statck [1] address=8049944
address=8049940
address=8049940

沒有留言: