Gcc: division by zero

I get division by zero on this line:

if (tim2_st_ovf < T2_PREK_250) 

These values ​​are defined as follows:

 volatile uint8_t tim2_st_ovf = 0; #define T2_PREK_250 ((250 * (F_CPU / 1000)) / ((UINT8_MAX + 1) * 1024)) #define F_CPU 16000000UL 

And UINT8_MAX is 255.

Why am I getting this? I calculated it several times on the calculator and get ~ 15. In addition, if I change 1024 to 1023, it does not show any errors.

+5
source share
1 answer

((UINT8_MAX + 1) * 1024) may become 0, because UINT8_MAX + 1 usually 256, and 256 * 1024 is 0 modulo 2 16 . So, if sizeof(int) == 2 on your architecture, then you get 0.

In typical modern desktop architectures with GCC, sizeof(int) == 4 , and you won't get division by 0.

To fix this, replace 1024 with 1024UL . This will work because the unsigned long guaranteed to reach 4294967295. (Thanks to Pascal Cuoc for his explanation.)

+7
source

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


All Articles