Function optimized to infinite loop at 'gcc -O2'

后端 未结 3 1478
故里飘歌
故里飘歌 2020-12-14 14:59

Context
I was asked the following puzzle by one of my friends:

void fn(void)
{
  /* write something after this comment so that the progr         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-14 15:14

    If the loop does get optimized out into an infinite loop, it could be due to static code analyzis seeing that your array is

    1. not volatile

    2. contains only 0

    3. never gets written to

    and thus it is not possible for it to contain the number 5. Which means an infinite loop.

    Even if it didn't do this, your approach could fail easily. For example, it's possible that some compiler would optimize your code without making your loop infinite, but would stuff the contents of i into a register, making it unavailable from the stack.

    As a side note, I bet what your friend actually expected was this:

    void fn(void)
    {
      /* write something after this comment so that the program output is 10 */
      printf("10\n"); /* Output 10 */
      while(1); /* Endless loop, function won't return, i won't be output */
      /* write something before this comment */
    }
    

    or this (if stdlib.h is included):

    void fn(void)
    {
      /* write something after this comment so that the program output is 10 */
      printf("10\n"); /* Output 10 */
      exit(0); /* Exit gracefully */
      /* write something before this comment */
    }
    

提交回复
热议问题