I have been trying to solve a bug in work for a while and finally I found it. It turns out that one function was passing a variable of size uint16_t to another function which accepts a variable of size uint8_t, even without any explicit casting.
This was intermittently causing an assert on lowers layers within the software whenever an invalid ID was detected.
The below code shows a much more simplified version of what happened.
The thing is that the caller function can't have an ID value greater than 0xFF even tho it has size of uint16_t. So, passing the value to the callee function almost all of the time, the value is valid.
The interesting thing is that the problem / assert only happened when size optimisation was enabled.
I'm interested to know what exactly could have happened here. I'm trying to understand it properly. It seems that the variable being passed is sometimes greater than 0xFF (but it shouldn't be) and then must get truncated when passed to the function resulting in an invalid ID.
Also, What is the effect of simply passing the variable like is done below versus casting the variable to uint8_t , like func((uint8_t)ID); ?
I'm surprised the compiler didn't even warn on this in my case.
EDITED : Code example with value of variable causing confusion
Many thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void func(uint8_t);
int main()
{
uint16_t ID;
// more code
// ID gets assigned a value from 0 to 0xFF somewhere
//....
func(ID);
return 0;
}
void func(uint8_t ID )
{
// Processing of ID
//........
//........
printf("%x\n", ID);
}