I'm trying to become "a real man", aka moving from C++ to C. Pointers and malloc get confusing at times. I'm using gcc without any flags, 64 bit linux.
So my first question is:
int* c;
int* d;
void* shared = malloc(sizeof(int)*2);
c = shared;
d = shared + sizeof(int);
*c = 123;
*d = 321;
printf("c: %p, *c: %i\n", (void*)c, *c);
printf("d: %p, *d: %i\n", (void*)d, *d);
printf("sizeof(c): %lu, sizeof(d): %lu\n", sizeof(c), sizeof(d));
outputs: c: 0x1c97050, *c: 123 d: 0x1c97054, *d: 321 sizeof(c): 8, sizeof(d): 8
Converting the two memory addresses to decimal and checking their difference gives 4. Meaning they are 4 bytes away from each other in the memory? So that means int is represented on 4 bytes, sizeof(int) = 4.
But a pointer (of any kind I guess but in our case to an int) is represented on 8 bytes, due the 64bit memory? Meaning I made a mistake by mallocing only 4 bytes instead of the required 8 bytes (int instead of int*).
But then how come I am not losing any data? Pure coincidence/luck?