Why does this division by zero error occur only in optimized code?

I just found an error, which, oddly enough, only happened when optimization ( g++ -O2) was turned on . This was Arithmetic exceptionin the following code when it intervalwas set to zero (from the command line argument):

for(int i = 0; i < n; ++i) {
  if((i + 1) % interval == 0) { // exception here
    DoSomething();
  }
}

Obviously, modulo the zero operation, an exception with a division into zero was generated, but why did this happen only when the code was compiled with the optimization turned on?

+3
source share
4 answers

undefined. , , undefined.

+13

.

const int, .

+1

, . -, ' 0.

for(int i = 0; i < n; ++i) {
  if (0==interval) { break; }
  if((i + 1) % interval == 0) { // exception here
    DoSomething();
  }
}

, . , "" .

0

, ? , . ? x86, arm, ppc? ? ..?

#include 
const int interval=BOB;
int main ( void )
{
    int i,n;
    n=10;
    for(i = 0; i < n; ++i)
    {
        if((i + 1) % interval == 0)
        { // exception here
            printf("%d\n",i);
        }
    }
    return(0);
}
gcc interval.c -DBOB=0 -O2 -o interval
interval.c: In function ‘main’:
interval.c:15: warning: division by zero

...

EDIT:

, , .

#include <stdio.h>
const int interval;
int main ( int argc, char *argv[] )
{
    int i,n;
    if(argc<2) return(1);
    interval=atoi(argv[1]);

    n=10;
    for(i = 0; i < n; ++i)
    {
        if((i + 1) % interval == 0)
        { // exception here
            printf("%d\n",i);
        }
    }
    return(0);
}
gcc -o interval interval.c
interval.c: In function ‘main’:
interval.c:7: error: assignment of read-only variable ‘interval’

.

, const , , , , . , , , , , .

EDIT:

#include <stdio.h>
int main ( int argc, char *argv[] )
{
const int interval;
    int i,n;
    if(argc<2) return(1);
    interval=atoi(argv[1]);

    n=10;
    for(i = 0; i < n; ++i)
    {
        if((i + 1) % interval == 0)
        { // exception here
            printf("%d\n",i);
        }
    }
    return(0);
}

gcc -c interval.c 
interval.c: In function ‘main’:
interval.c:7: error: assignment of read-only variable ‘interval’

, , , , , . , , ,.text (rom/flash), , , , const / . , - , , / ( , gcc, gcc) (99.999999999999% , , , , , ). const , , . .

EDIT 2:

unsigned int fun (unsigned int a)
{
    const unsigned int b = 7;
    * (unsigned int *) & b = 5;
    return (a + b);
}

compile above with optimization and you will get:

    .global fun
fun:
    add r0, r0, # 7
    bx lr

as expected, const does read only b. without const:

unsigned int fun (unsigned int a)
{
    unsigned int b = 7;
    * (unsigned int *) & b = 5;
    return (a + b);
}
    .global fun
fun:
    add r0, r0, # 5
    bx lr

I wonder, but it never demonstrates how const works.

0
source

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


All Articles