Skip to content

Instantly share code, notes, and snippets.

@tribals
Created September 26, 2021 23:58
Show Gist options
  • Save tribals/d9da30f568b9e1104291f2b7440f1954 to your computer and use it in GitHub Desktop.
Save tribals/d9da30f568b9e1104291f2b7440f1954 to your computer and use it in GitHub Desktop.
Example of C pointers overlap when casted to another (wider, in terms of bytes) type

Build it:

$ make overlap

Run it:

$ ./overlap 
pointer: 0x1d202a0
(4-byte ints)
0:	0xCAFEBABE
1:	0xDEADBEEF
2:	0x00000000
3:	0x0000FEED
(treated as 8-byte int) 0: 0xDEADBEEFCAFEBABE
(treated as 8-byte int) 1: 0x0000FEED00000000
#include <stdio.h>
#include <stdlib.h>
#define COUNT 4
#define FMT_HEX_LOWER_X(f) "0x%0" f "X"
#define FMT_CONV_HEX_WIDTH(x) (sizeof(x) * 2)
main() {
int32_t *p = malloc(sizeof *p * COUNT);
*p = 0xCAFEBABE;
*(p + 1) = 0xDEADBEEF;
*(p + 3) = 0xFEED;
printf("pointer: %p\n", p);
printf("(4-byte ints)\n");
for (int i = 0; i < COUNT; i++) {
printf("%d:\t" FMT_HEX_LOWER_X("*") "\n", i, FMT_CONV_HEX_WIDTH(*(p + i)), *(p + i));
}
printf("(treated as 8-byte int) 0: " FMT_HEX_LOWER_X("*l") "\n", FMT_CONV_HEX_WIDTH(*(int64_t *)p), *(int64_t *)p);
printf("(treated as 8-byte int) 1: " FMT_HEX_LOWER_X("*l") "\n", FMT_CONV_HEX_WIDTH(*(int64_t *)(p + 2)), *(int64_t *)(p + 2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment