You could try with:
ptrdiff_t bytes = ((char *)p2) - ((char *)p1);
But this only works as expected if the pointers you subtract point to the same single piece of memory or within it. For example:
This will not work as expected:
char *p1 = malloc(3); // "ABC", piece 1
char *p2 = malloc(3); // "DEF", piece 2
char *p3 = malloc(3); // "GHI", piece 3
ptrdiff_t bytes = p3 - p1; // ABC ... DEF ... GHI
// ^ ^
// p1 p3
// Or:
// GHI ... ABC ... DEF
// ^ ^
// p1 p3
// Gives on my machine 32
printf("%td\n", bytes);
Because:
- The malloc implementation could allocate some additional bytes for internal purposes (e.g. memory barrier). This would effect the outcome bytes.
- It is not guaranteed that p1 < p2 < p3. So your result could be negative.
However this will work:
char *p1 = malloc(9); // "ABCDEFGHI", one piece of memory
char *p2 = p1 + 3; // this is within the same piece as above
char *p3 = p2 + 3; // this too
ptrdiff_t bytes = p3 - p1; // ABC DEF GHI
// ^ ^
// p1 p3
// Gives the expected 6
printf("%td\n", bytes);
Because:
- The allocated 9 Bytes will always be in one piece of memory. Therefore this will always be true: p1 < p2 < p3 and since the padding/additional bytes are on the start/end of the piece subtraction will work.