Reputation: 61
I wrote the program to find out about memory management in C. But I noticed something strange about this program: Why is the variable "a" in memory location 6487580 and not in memory location 6487576.
Because if a pointer is 8 bytes, then it should only reach up to this address. And then the variable "a" would have space there.
#include <stdio.h>
#include <stdlib.h>
int main(){
int a=10;
int *ptr;
ptr=&a;
int **ptrptr;
ptrptr=&ptr;
printf("adress:\n");
printf("Adress a: %i\n",&a);
printf("Sizeof a: %i\n",sizeof(a));
printf("Adress ptr: %i\n",&ptr);
printf("Sizeof ptr: %i\n",sizeof(ptr));
printf("Adress ptrptr: %i\n",&ptrptr);
printf("Sizeof ptrptr: %i\n",sizeof(ptrptr));
return 0;
}
Upvotes: 1
Views: 234
Reputation: 50017
Memory alignment. It is likely that the computer you're running on can retrieve data from memory faster or more efficiently if it's stored on a doubleword (8 byte) boundary, or at least the compiler is programmed to make that assumption. If you examine the addresses in binary you'll note they all end in 00
, putting them on a doubleword boundary.
Thus, ptrptr
is stored on a doubleword boundary at the low-order location and takes 8 bytes. ptr is stored next in memory, and occupies the next 8 bytes. Then 4 bytes are skipped (6487576-6487579) so that a
will be aligned on a doubleword boundary at 6487580.
Your compiler may have flags which instruct it to align variables on word or doubleword boundaries - or, conversely, to ignore such alignment concerns. Consult your local documentation for such information.
Upvotes: 2