What is the difference allocate a memory with new global and local
Hi All,
I am confused why it happens? Please solve the problem…….. I generate a assembly code for following C++ code: Allocate memory with new local Case 1: CPP Code int main() { float * fptr = new float; return 1; } Corresponding Assembly Code for new and fptr li %r3,4 bl _Znwj Allocate memory with new Global Case 2: CPP Code float * fptr = new float; int main() { return 1; } Corresponding Assembly Code for new and fptr .align 2 .type _Z41__static_initialization_and_destruction_0ii, @function _Z41__static_initialization_and_destruction_0ii: stwu %r1,-16(%r1) mflr %r0 cmpwi %cr7,%r3,1 stw %r0,20(%r1) beq- %cr7,.L9 .L7: lwz %r4,20(%r1) addi %r1,%r1,16 mtlr %r4 blr .L9: xoris %r3,%r4,0xffff cmpwi %cr0,%r3,-1 bne %cr0,.L7 li %r3,4 bl _Znwj lwz %r4,20(%r1) lis %r9,fptr@ha addi %r1,%r1,16 stw %r3,fptr@l(%r9) mtlr %r4 blr .size _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii .align 2 .type _GLOBAL__I_fptr, @function _GLOBAL__I_fptr: li %r4,0 li %r3,1 ori %r4,%r4,65535 b _Z41__static_initialization_and_destruction_0ii .size _GLOBAL__I_fptr, .-_GLOBAL__I_fptr .globl fptr .section .sbss,"aw",@nobits .align 2 .type fptr, @object .size fptr, 4 fptr: .zero 4 |
I'm not familiar with that flavour of assembler, but there's still a "li %r3,4 ; bl _Znwj" set of instructions in both versions, the only differences are (i) when those instructions are executed and (ii) what's done with the pointer.
In the first version, the memory only gets allocated as part of the main() function, but in the second version the memory is allocated before main() is ever entered - gcc inserts code before (and after) your main() function to do this. And when you call new in your main() function the returned pointer is (presumably) moved onto the stack, but if fptr is global, "lwz %r4,20(%r1)" moves the pointer to the allocated memory to where fptr is in memory. |
All times are GMT -5. The time now is 02:39 PM. |