I have been writing C/C++ code for my work for over 4 years now. Yet I tend to do simple mistakes. How is that possible? Well, because C is full of pitfalls...
I will post some buggy codes here, as warning examples. I will not tell what the bugs are - yet. I will reveal that later in this blog, so you can try finding the problems yourself :) And naturally solutions can be posted in comments.
So mistake 1. It was a simple bit masking in C.
I had an unsigned int coming in a function, and I wanted to replace certain bytes from it. So I decided that I'll write a function, which gets the original unsigned int, indication about which bytes should be changed, and what those bytes should be changed to.
0xXXXXXXXX original value
0x00FF0000 bits to change
0x00AB0000 What to change the bits.
unsigned int changebytes(unsigned int const &real, unsigned int const &changedbits, unsigned int &changeto)
unsigned int tmp,tmp2;
/*get the bits which are not changed
(bit's value will be inverted when
XORed with bit 1)*/
/*null the bits which will be changed.
(AND will set result to zero, if one of the bits
'anded' is zero).*/
tmp2=(real & tmp);
/*add changeto bits in the tmp
(OR will 'sum' the bytes).*/
return (tmp2 | changeto);
Well, this actually introduces (at least) 2 bugs.