开发者

stack layout for process

why is the output 44 instead of 12, &x,eip,ebp,&j should be the stack layout for the code given below i guess, if so then it must have 12 as output, but i am getting it 44? so help me understand the concept,altough the base pointer is relocated for every instant of execution, the relative must remain unchan开发者_如何学Goged and should not it be 12?

int main() {
    int x = 9;
    // printf("%p is the address of x\n",&x);
    fun(&x );
    printf("%x is the address of x\n", (&x));
    x = 3;
    printf("%d x is \n",x);
    return 0;
}

int fun(unsigned int *ptr) {    
    int j;
    printf("the difference is  %u\n",((unsigned int)ptr -(unsigned int) &j));
    printf("the address of j is %x\n",&j);

    return 0;
}


You're assuming that the compiler has packed everything (instead of putting things on specific alignment boundaries), and you're also assuming that the compiler hasn't inlined the function, or made any other optimisations or transformations.

In summary, you cannot make any assumptions about this sort of thing, or rely on any particular behaviour.


No, it should not be 12. It should not be anything. The ISO standard has very little to say about how things are arranged on the stack. An implementation has a great deal of leeway in moving things around and inserting padding for efficiency.

If you pass it through your compiler with an option to generate he assembler code (such as with gcc -S), it will become evident as to what's happening here.

fun:
    pushl   %ebp
    movl    %esp, %ebp
    subl    $40, %esp            ;; this is quite large (see below).
    movl    8(%ebp), %edx
    leal    -12(%ebp), %eax
    movl    %edx, %ecx
    subl    %eax, %ecx
    movl    %ecx, %eax
    movl    %eax, 4(%esp)
    movl    $.LC2, (%esp)
    call    printf
    leal    -12(%ebp), %eax
    movl    %eax, 4(%esp)
    movl    $.LC3, (%esp)
    call    printf
    movl    $0, %eax
    leave
    ret

It appears that gcc is pre-generating the next stack frame (the one going down to printf) as part of the prolog for the fun function. That's in this case. Your compiler may be doing something totally different. But the bottom line is: the implementation can do what it likes as long as it doesn't violate the standard.

That's the code from optimisation level 0, by the way, and it gives a difference of 48. When I use gcc's insane optimisation level 3, I get a difference of 4. Again, perfectly acceptable, gcc usually does some pretty impressive optimisations at that level.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜