Why doesn't my C ++ compiler optimize this memory?

I created this program. It is of no interest, but uses computing power.

Looking at the output with help objdump -d, I see three calls randand corresponding instructions movtowards the end, even when compiling with O3.

Why does the compiler not understand that the memory will not be used, and just replace the bottom half with while(1){}? I use gcc, but what interests me most is what the standard requires.

/*
 * Create a program that does nothing except slow down the computer.
 */
#include <cstdlib>
#include <unistd.h>

int getRand(int max) {
  return rand() % max;
}

int main() {
  for (int thread = 0; thread < 5; thread++) {
    fork();
  }
  int len = 1000;
  int *garbage = (int*)malloc(sizeof(int)*len);
  for (int x = 0; x < len; x++) {
    garbage[x] = x;
  }
  while (true) {
    garbage[getRand(len)] = garbage[getRand(len)] - garbage[getRand(len)];
  }
}
+4
source share
4 answers

GCC , . , garbage , GCC :

.L4:
    call    rand
    call    rand
    call    rand
    jmp .L4

rand ( , ), .

GCC , rand, rand, . , , .

+10

, rand() , .

, , .

, , . , - .

+5

undefined, . .

++ 14 1.10/27:

, :

  • ,
  • - ,
  • .

[Note. This is intended to allow compiler transformations, such as removing empty loops, even if termination is not possible. -end note]

I would not say what rand()is considered an I / O function.

Question related to us

+3
source

Leave a chance to crash when the array overflows! The compiler will not reflect on the range of outputs getRand.

0
source

Source: https://habr.com/ru/post/1609536/


All Articles