background

We define A variable A, modify another variable B, cause the value of A to be modified, we call this memory pollution.

case

In the following program, the normal expected output would be: 97 98 256, but the correct result is 1 0 256

Int * PTR = (int *)&b; Here, a strong conversion to &b contaminates a’s memory

Address A is larger than address B (the heap allocates addresses from low to high, and the stack allocates addresses from high to low)

#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;
}
Copy the code

validation

We through GDB debugging, print out the address of each variable GDB usage introduction

$ 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
Copy the code

We call * PTR = 256; I’m going to put a break point here, and then I’m going to look at what happens to A and B before and after execution

We first look at memory before the breakpoint using the GDB command x/1tb &a

  • aThe address of the0x7ffeefbff55bThe value is decimal97
  • bThe address of the0x7ffeefbff55aThe value is decimal98

Conclusion: ** A’s address is ** higher than B’s address

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

Then we do * PTR = 256; After this sentence, check again

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

After PTR is set to 245, the memory value is 00000000 00000001 00000000 00000000

The PTR is an int* and occupies 4 bytes. The address of A is one byte higher than that of the PTR, so it is within 4 bytes.

The original post was posted on GitHub

link

  • GDB views memory
  • MAC installation GDB