开发者

stack memory allocation and alignment issues

开发者 https://www.devze.com 2023-01-31 06:27 出处:网络
Here is the sample program and its output. typedef struct{ char name[30]; int empno; 开发者_如何学Pythonint sal;

Here is the sample program and its output.

typedef struct{
    char name[30];
    int empno;
  开发者_如何学Python  int sal;
}empd, * empdPtr;

int main(){
    int x = 1;
    char y = 2;
    int z = 3;
    empd e;
    empdPtr ep = &e;

    printf("sizeof ep = %d e = %d \n",sizeof(ep),sizeof(e));
    printf("Address of e = %u, ep = %u x = %u y = %u z = %u\n",&e,&ep,&x,&y,&z);
    printf("Address of e.name = %u e.empno = %u e.sal = %u \n",&e.name,&e.empno,&e.sal);
    return 0;
}

$ ./a.exe
sizeof ep = 4 e = 40
Address of e = 2289536, ep = 2289532 x = 2289596 y = 2289595 z = 2289588
Address of e.name = 2289536 e.empno = 2289568 e.sal = 2289572

Here the difference between address of &e and &z is 52. But the sizeof(e) is 40. Why compiler added 12 more bytes even though 40 bytes is enough?


Compilers are at liberty to lay out memory as they see fit in the interests of better performance, for example, or whatever it is that is motivating the code generation. On an OS with very limited resources the compiler may elect to pack rather than align for access speed. Perhaps there are some implicit local variables being produced by the compiler. There are lots of possible reasons for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消