# 你可能没留意到的”大坑” [内存污染]

## 你可能没留意到的大坑 [内存污染]

#### 案例

,但正确的结果却是 `1 0 256`
，意不意外，惊不惊喜

`a`

)

```#include <stdio.h>
int main(void)
{
char a = 'a', b = 'b';
int *ptr = (int *)&b;
*ptr = 256;
printf("%d,%d,%d \n", a, b, *ptr); // 1 0 256
return 0;
}

#### 验证

```\$ gdb a.out
(gdb) b 7
Breakpoint 1 at 0x100000f47: file test.c, line 7.
(gdb) b 11
Breakpoint 2 at 0x100000f77: file test.c, line 11.
Thread 2 hit Breakpoint 1, main () at test.c:7
7           int *ptr = (int *)&b;
(gdb) x/1tb &a
0x7ffeefbff55b: 01100001
(gdb) x/1tb &b
0x7ffeefbff55a: 01100010
(gdb) n
8           *ptr = 256;
(gdb) n
10          printf("%d,%d,%d \n", a, b, *ptr); // 1 0 256
(gdb) n
1,0,256
Thread 2 hit Breakpoint 2, main () at test.c:11
11          return 0;
(gdb) x/1tb &a
0x7ffeefbff55b: 00000001
(gdb) x/1tb &b
0x7ffeefbff55a: 00000000
(gdb) x/4tb ptr
0x7ffeefbff55a: 00000000        00000001        00000000        00000000

, `b`

• `a`
的地址 `0x7ffeefbff55b`
值为十进制 `97`
• `b`
的地址 `0x7ffeefbff55a`
值为十进制 `98`

#### 结论： a 的地址比 b 的地址高

```(gdb) x/1tb &a
0x7ffeefbff55b: 01100001
(gdb) x/1tb &b
0x7ffeefbff55a: 01100010

```(gdb) x/1tb &a
0x7ffeefbff55b: 00000001
(gdb) x/1tb &b
0x7ffeefbff55a: 00000000
(gdb) x/4tb ptr
0x7ffeefbff55a: 00000000        00000001        00000000        00000000

ptr赋值245后，内存中值为 `00000000 00000001 00000000 00000000`