先看代码(a.c):
#include <stdio.h>
int main(int argc, char* argv[])
{
int a[4]={1,2,3,4};
int *ptr1=(int*)(&a+1);
int *ptr2=(int*)((int)a+1);
int *ptr3=(int*)(a+1);
printf("a = %x, &a = %x, &a+1 = %x, (int)a+1 = %x\n", a, &a, &a+1, (int)a+1);
printf("ptr1 = %x, ptr2 = %x, ptr3 = %x, &ptr1[-1] = %x\n", ptr1, ptr2, ptr3, &ptr1[-1]);
printf("ptr1[-1] = %x, *ptr2 = %x, *ptr3 = %x\n",ptr1[-1],*ptr2, *ptr3);
return 0;
}
再看调试情况:
[zcm@t #81]$make clean
rm -f *.o a
[zcm@t #82]$make
gcc -g -c -o a.o a.c
gcc -g -o a a.o
[zcm@t #83]$gdb a
GNU gdb (GDB) Fedora (7.0-3.fc12)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt/hgfs/Linux_Share/t/a...done.
(gdb) list
1 #include <stdio.h>
2
3 int main(int argc, char* argv[])
4 {
5 int a[4]={1,2,3,4};
6 int *ptr1=(int*)(&a+1);
7 int *ptr2=(int*)((int)a+1);
8 int *ptr3=(int*)(a+1);
9 printf("a = %x, &a = %x, &a+1 = %x, (int)a+1 = %x\n", a, &a, &a+1, (int)a+1);
10 printf("ptr1 = %x, ptr2 = %x, ptr3 = %x, &ptr1[-1] = %x\n", ptr1, ptr2, ptr3, &ptr1[-1]);
(gdb) list
11 printf("ptr1[-1] = %x, *ptr2 = %x, *ptr3 = %x\n",ptr1[-1],*ptr2, *ptr3);
12
13 return 0;
14 }(gdb) b 5
Breakpoint 1 at 0x80483ce: file a.c, line 5.
(gdb) b 11
Breakpoint 2 at 0x8048472: file a.c, line 11.
(gdb) b 13
Breakpoint 3 at 0x80484a0: file a.c, line 13.
(gdb) run
Starting program: /mnt/hgfs/Linux_Share/t/a
Breakpoint 1, main (argc=1, argv=0xbffff2f4) at a.c:5
5 int a[4]={1,2,3,4};
Missing separate debuginfos, use: debuginfo-install glibc-2.11-2.i686
(gdb) c
Continuing.
a = bffff214, &a = bffff214, &a+1 = bffff224, (int)a+1 = bffff215
ptr1 = bffff224, ptr2 = bffff215, ptr3 = bffff218, &ptr1[-1] = bffff220
Breakpoint 2, main (argc=1, argv=0xbffff2f4) at a.c:11
11 printf("ptr1[-1] = %x, *ptr2 = %x, *ptr3 = %x\n",ptr1[-1],*ptr2, *ptr3);
(gdb) c
Continuing.
ptr1[-1] = 4, *ptr2 = 2000000, *ptr3 = 2
Breakpoint 3, main (argc=1, argv=0xbffff2f4) at a.c:13
13 return 0;
(gdb) x /24xb a
0xbffff214: 0x01 0x00 0x00 0x00 0x02 0x00 0x00 0x00
0xbffff21c: 0x03 0x00 0x00 0x00 0x04 0x00 0x00 0x00
0xbffff224: 0x24 0xf2 0xff 0xbf 0x15 0xf2 0xff 0xbf
(gdb)
最后看图解: