Can you spot the bug?

I have been “lucky” enough to write code like this a few days ago:

bool side[max_lines][max_lines];
if(memcmp(side[i], side[j], sizeof(side[0][0] * lines)) == 0) return true;

Now it’s obvious to me why it didn’t work as expected. But can you find the bug? If you got it, what techniques do you use to avoid problems of this kind in your code?

//Note: the bug image is from Slashdot.

3 Responses to Can you spot the bug?

  1. Alex says:

    Well, I tried to process this without re-checking the specs of the functions or trying the code (i.e. cu ochiul neinarmat)

    lines should be taken out of the call to sizeof and instead multiplied with what it returns.

    In your code sizeof will return the size of the result (while you expect the size of the buffer). I don’t know what the result of bool*int is, perhaps bool will be cast into int, thus the result will be an int. It’s nice that C/C++ gives you the chance to do all that magic.

    “C gives you enough rope to hang yourself”, or
    “C gives you enough rope to shoot yourself in the foot”.

    And I like this one too – “playing with pointers is like juggling with pieces of soap in a shower in prison” :-)

    It should be

    sizeof(side[0][0]) * lines

    Disclaimer: If I am wrong, I take my words back :-)

  2. Alex says:

    p.s. in SOVIET Russia bug find YOU!!

  3. Constantin says:

    You are right :)
    sizeof(bool * int) returns 4 on GCC 4.1, so it compared 4 bytes only, instead of comparing the whole array rows.

    In the “shoot yourself in the foot” spirit:
    C: You shoot yourself in the foot.
    C++: You accidentally create a dozen instances of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can’t tell which are bitwise copies and which are just pointing at others and saying “That’s me, over there.”

%d bloggers like this: