Created
October 4, 2015 12:57
-
-
Save goyusia/d0b30c39e5a53d7eb002 to your computer and use it in GitHub Desktop.
Compiler-dependent infinitely loop bug by stack allocation policy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| g++ main.cpp -W -Wall | |
| ./a.out | |
| addr x : 7ffc853ffcf4 | |
| addr y : 7ffc853ffcf8 | |
| addr diff: -4 | |
| addr i : 7ffc853ffce4 | |
| addr array: 7ffc853ffcf0 | |
| curr addr : 7ffc853ffcf0 | |
| curr addr : 7ffc853ffcf4 | |
| curr addr : 7ffc853ffcf8 | |
| clang main.cpp -W -Wall | |
| ./a.out | |
| addr x : 7ffd5dfc3abc | |
| addr y : 7ffd5dfc3ab8 | |
| addr diff: 4 | |
| addr i : 7ffd5dfc3ab8 | |
| addr array: 7ffd5dfc3ab0 | |
| curr addr : 7ffd5dfc3ab0 | |
| curr addr : 7ffd5dfc3ab4 | |
| curr addr : 7ffd5dfc3ab0 | |
| curr addr : 7ffd5dfc3ab4 | |
| curr addr : 7ffd5dfc3ab0 | |
| ERROR: Infinitely Loop!!! | |
| */ | |
| /* | |
| Reference | |
| http://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack | |
| */ | |
| #include <cstdio> | |
| void simple_addr_order() | |
| { | |
| int x; | |
| int y; | |
| int diff = (unsigned long)&x - (unsigned long)&y; | |
| printf("addr x : %lx\n", (unsigned long)&x); | |
| printf("addr y : %lx\n", (unsigned long)&y); | |
| printf("addr diff: %d\n", diff); | |
| } | |
| void buggy_loop() | |
| { | |
| const int ARRAY_SIZE = 2; | |
| int i = 1234; | |
| int array[ARRAY_SIZE]; | |
| printf("addr i : %lx\n", (unsigned long)&i); | |
| printf("addr array: %lx\n", (unsigned long)array); | |
| int loop_count = 0; | |
| for(i = 0 ; i <= ARRAY_SIZE ; ++i) { | |
| array[i] = 0; | |
| printf("curr addr : %lx\n", (unsigned long)&array[i]); | |
| loop_count++; | |
| if(loop_count > ARRAY_SIZE + 2) { | |
| printf("ERROR: Infinitely Loop!!!\n"); | |
| break; | |
| } | |
| } | |
| } | |
| int main() | |
| { | |
| simple_addr_order(); | |
| buggy_loop(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment