Integer overflow error

This is part of my OpenGL code, I get an error:

struct Ball {
    float x;
    float y;
    float rot;
    float dir;
    bool rmv;
    Ball* next;
};

Ball* curBall;
void addBall() {
    if (balls==NULL) {
        balls=new Ball;
        balls->next=NULL;
        curBall=balls;
    } else {
        curBall->next=new Ball;
        curBall=curBall->next;
        curBall->next=NULL;
    }
    curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1;
    curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1;
    curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1;
    curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1;
    curBall->rmv=false;
}

error :
In function ‘void addBall()’:
file.cpp:120: warning: integer overflow in expression
file.cpp:121: warning: integer overflow in expression
file.cpp:122: warning: integer overflow in expression
file.cpp:123: warning: integer overflow in expression
+3
source share
4 answers

Try converting RAND_MAXto float before adding to it.

curBall->x=((float)rand()/( ((float)RAND_MAX) +1))*(ww-1) +1;

et cetera. RAND_MAXoften equal INT_MAX, the largest value may contain an integer, adding 1 to it, while it is still considered an integer, pushing it along the integer limit.

+12
source

It is probably RAND_MAX + 1overflowing, as RAND_MAX might be == INT_MAX.

+2
source

, RAND_MAX INT_MAX, RAND_MAX+1 . , .

+2

It may depend on your compiler if RAND_MAX == MAX_INT and then RAND_MAX + 1 will overflow.

+2
source

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


All Articles