A simple program to allocate and free heap memory:
int main(int argc, char **argv) {
char *b1, *b2, *b3, *b4, *b_large;
b1 = malloc(8);
memset(b1, 0xaa, 8);
b2= malloc(16);
memset(b2, 0xbb, 16);
b3 = malloc(25);
memset(b3, 0xcc, 25);
b4= malloc(1000);
memset(b4, 0xdd, 1000);
free(b1);
free(b2);
free(b3);
free(b4);
Before first free():
(gdb) x/20gx 0x555555559290
0x555555559290: 0x0000000000000000 0x0000000000000021
0x5555555592a0: 0xaaaaaaaaaaaaaaaa 0x0000000000000000
0x5555555592b0: 0x0000000000000000 0x0000000000000021
0x5555555592c0: 0xbbbbbbbbbbbbbbbb 0xbbbbbbbbbbbbbbbb
0x5555555592d0: 0x0000000000000000 0x0000000000000031
0x5555555592e0: 0xcccccccccccccccc 0xcccccccccccccccc
0x5555555592f0: 0xcccccccccccccccc 0x00000000000000cc
0x555555559300: 0x0000000000000000 0x00000000000003f1
0x555555559310: 0xdddddddddddddddd 0xdddddddddddddddd
0x555555559320: 0xdddddddddddddddd 0xdddddddddddddddd
And after first free():
(gdb) x/20gx 0x555555559290
0x555555559290: 0x0000000000000000 0x0000000000000021
0x5555555592a0: 0x0000000555555559 0xd13e7903c502febc
0x5555555592b0: 0x0000000000000000 0x0000000000000021
0x5555555592c0: 0xbbbbbbbbbbbbbbbb 0xbbbbbbbbbbbbbbbb
0x5555555592d0: 0x0000000000000000 0x0000000000000031
0x5555555592e0: 0xcccccccccccccccc 0xcccccccccccccccc
0x5555555592f0: 0xcccccccccccccccc 0x00000000000000cc
0x555555559300: 0x0000000000000000 0x00000000000003f1
0x555555559310: 0xdddddddddddddddd 0xdddddddddddddddd
0x555555559320: 0xdddddddddddddddd 0xdddddddddddddddd
I was expecting to see readable forward and back pointers in the second line of memory, and
in the third line 0x20 in both 8-bytes segments.
Can anyone explain why the free() function would behave in this way?