I have the following program:
Code:
#include <stdio.h>
#include <stdlib.h>
struct myStruct {
char myData[50];
};
void print_addr(void *addr, char *msg);
int main(void)
{
char *test_char = malloc(500);
char *test_char2 = malloc(5);
struct myStruct *test_data = malloc(sizeof(struct myStruct));
struct myStruct *test_data2 = malloc(sizeof(struct myStruct));
struct myStruct *a = test_data + 0;
struct myStruct *b = test_data + 25;
struct myStruct *c = test_data2 + 5;
print_addr(b, "b");
print_addr(c, "c");
print_addr(test_char, "test_char");
print_addr(test_char2, "test_char2");
unsigned long int result = test_char2 - test_char;
printf("test_char2 - test_char: %lu\n", result);
print_addr(test_data, "test_data addr");
print_addr(test_data2, "test_data2 addr");
unsigned long int difference = b - a;
unsigned long int difference_2 = b - c;
unsigned long int difference_3 = c - b;
printf("Difference: %lu\n", difference);
printf("Difference 2 (b - c): %lu\n", difference_2);
printf("Difference 2 (c - b): %lu\n", difference_3);
free(test_char);
free(test_data);
return EXIT_SUCCESS;
}
void print_addr(void *addr, char *msg)
{
if(NULL == msg)
{
return;
}
printf("%s : %p\n", msg, addr);
return;
}
This is obviously a test program. I'm trying to understand pointer arithmetic with subtraction. It produces the following output:
:undefined_behavior user$ ./ptr_arith_ub
b : 0x7fa591403182
c : 0x7fa591402dda
test_char : 0x7fa591402d90
test_char2 : 0x7fa591402c90
test_char2 - test_char: 18446744073709551360
test_data addr : 0x7fa591402ca0
test_data2 addr : 0x7fa591402ce0
Difference: 25
Difference 2 (b - c): 1475739525896764148
Difference 2 (c - b): 16971004547812787468
You can see that the math results dont make sense given the numbers. why is b - c 1475739525896764148? 0x7fa591403182 - 0x7fa591402dda clearly should not be that. Thanks.