2021-10-06 05:40 AM
Is there a way to prevent a crash while there is a division at zero.
For example when there is a division by zero it will return zero
2021-10-06 05:51 AM
Welcome, @Ecohe, to the community!
Yes, of course. Unfortunately, this has a somewhat unpleasant side effect because it costs additional code and therefore processing time - you can check the divisor for zero before dividing
Regards
/Peter
2021-10-06 05:57 AM
can give an example
2021-10-06 06:05 AM
There are tons of examples, e.g. here.
The implementation also depends on the number type (integer, floating, ...).
Regards
/Peter
2021-10-06 06:32 AM
sorry it's not helped . I know it will better to make sure it not zero before the division. i am looking for a way to make a trap if this occurred it will return zero.
2021-10-06 07:58 AM
What do you mean, "it's not helped" ?
What, exactly, did you do?
In what way(s), exactly, were the results unsatisfactory for you?
"i am looking for a way to make a trap if this occurred"
What chip are you using? Have you looked to see what exception occurs (ie, what vector is called) when a divide-by-zero happenss?
2021-10-06 08:18 AM
Sorry for the lack of understanding
I have a big project that I am converting it from Keil and when it run there it returning automatically a zero when division by zero accured.
I can not find all the places and situations when these cases occur.
I am looking for a way to do it the same like keil do (automaticly).
when it occurs in STM32IDE(g++) it goes to HardFault_Handler
for example:
Keil:
int a=1;
a=a /0;
//a got 0
STM32IDE it (g++):
int a=1;
a=a /0;
// goes to HardFault_Handler
Chip:
STM32F413VGTX
Thanks'
2021-10-06 08:41 AM
"I am looking for a way to do it the same like keil do"
So have you asked Keil how they do it?
"when it occurs in STM32IDE(g++) it goes to HardFault_Handler"
Are you sure it's a HardFault ? Isn't that a Usage Fault?
Take a look at https://www.keil.com/appnotes/files/apnt209.pdf
Also: https://wiki.segger.com/Cortex-M_Fault#Division_By_Zero
https://www.google.com/search?q=cortex-m4+divide-by-zero+fault
2021-10-06 10:20 AM
Probably not UsageFault unless explicitly enabled.
HardFault is a trap..
Generally the more wisen approach is to sanity check math that might realistically cause the error. Returning zero could realistically cascade the math failure, silently.
It's more probable the issue wasn't address in the original code, because the failure wasn't detected/addressed due to lack of awareness.
2021-10-06 10:46 AM
"Probably not UsageFault unless explicitly enabled"
Yes - that is mentioned in the Segger article, at least.