还是照旧,先贴两段代码说明问题.
- #include <stdio.h>
- typedef struct{
- int a;
- int b;
- char c;
- int d;
- }*p_Test;
- int main(){
- printf("%#X\n",&(((p_Test)0)->d));
- printf("%#X\n",&(*((int *)0)));
- return 0;
- }
对应汇编:
- .file "test1.c"
- .section .rodata
- .LC0:
- .string "%#X\n"
- .text
- .globl main
- .type main, @function
- main:
- pushl %ebp
- movl %esp, %ebp
- andl $-16, %esp
- subl $16, %esp
- movl $.LC0, %eax
- movl $12, 4(%esp)
- movl %eax, (%esp)
- call printf
- movl $.LC0, %eax
- movl $0, 4(%esp)
- movl %eax, (%esp)
- call printf
- movl $0, %eax
- leave
- ret
- .size main, .-main
- .ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
- .section .note.GNU-stack,"",@progbits
另外一段为:
- #include <stdio.h>
- typedef struct{
- int a;
- int b;
- char c;
- int d;
- }*p_Test;
- int main(){
- printf("%#X\n",(((p_Test)0)->d));
- printf("%#X\n",(*((int *)0)));
- return 0;
- }
对应汇编为:
- .file "test1.c"
- .section .rodata
- .LC0:
- .string "%#X\n"
- .text
- .globl main
- .type main, @function
- main:
- pushl %ebp
- movl %esp, %ebp
- andl $-16, %esp
- subl $16, %esp
- movl $0, %eax
- movl 12(x), %edx
- movl $.LC0, %eax
- movl %edx, 4(%esp)
- movl %eax, (%esp)
- call printf
- movl $0, %eax
- movl (%eax), %edx
- movl $.LC0, %eax
- movl %edx, 4(%esp)
- movl %eax, (%esp)
- call printf
- movl $0, %eax
- leave
- ret
- .size main, .-main
- .ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
- .section .note.GNU-stack,"",@progbits
今天老师讲了Linux源码中include/linux/kernel.h中的container_of,代码是这样的:
/**
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*
*/
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
开始不太理解,他以0作为指针地址去访问一个结构,难道不会发生段错误吗?后来自己又写了个测试,发现如果用任意数作为的指针不是进行实质性的内存访问的话,那么编译器是允许的,怎么说?看上面对照的汇编代码就知道了,编译器在编译成汇编代码的时候就已经把值计算出来了,而不是在运行时作为内存地址偏移进行操作,所以...哎,我也说不清楚,反正这些细节,自己长点记性...按老师那句话,领会精神!
阅读(1476) | 评论(1) | 转发(1) |