0

I was trying to understand structure padding , so i wrote a simple program as written below and i executed it . just to make clear i made two copy of this program program1.c and program2.c and executed both together to see the member address but something strange came up Both program giving me same result , as like having exactly same addresses I want to know what exactly happening internally ?

Program1.c

    #include<stdio.h>
struct pad{
short int a[5];
int b;
char c;
} y;

int main()
{
    int size = sizeof(y); 
    printf (" size %d byte",size);

    y.b = 10;
    printf ("\n address of member 1 is  %d \n",&y.a);
    printf (" address of member 2 is  %d \n",&y.b);
    printf (" address of member 3 is  %d \n",&y.c);    


    getch ();    
}

Output of the program

size 20 byte
 address of member 1 is  4210784
 address of member 2 is  4210796
 address of member 3 is  4210800

This is program2.c

include<stdio.h>

struct pad{

short int a[5];
int b;
char c;
} x;

int main()
{
    int size = sizeof(x); 
    printf (" size %d byte",size);


    printf ("\n address of mem 1 is  %d \n",&x.a);
    printf (" address of mem 2 is  %d \n",&x.b);
    printf (" address of mem 3 is  %d \n",&x.c);
//    printf (" size %d byte",size);



    getch ();    
}

Output of second program

size 20 byte
 address of member 1 is  4210784
 address of member 2 is  4210796
 address of member 3 is  4210800

I am using windows 7 32 bit architecture , and Dev-c++

user143252
  • 31
  • 8

1 Answers1

8

This is the result of virtual memory. Roughly, virtual memory provides each running program with the illusion that all of the system's memory is at its disposal. It presents each program with an abstract virtual address space, and the operating system and the CPU map addresses in the abstract virtual memory space to locations in physical memory. The physical memory may be RAM or it may be slow storage like blocks on a disk drive. One side effect of this is that multiple copies of the same running program all seem to have the same addresses for their variables. You may want to read What Every Programmer Should Know About Memory for more detailed information.