The following piece of code contains a trivial error... twice.

        int v;
        char buf[11], *p;
        memset(buf, 0, sizeof(buf));

        /* Fill buf with a string */

        v = strtoul(buf, &p, 16);
        p = NULL;      // <--- This is wrong!!
        if (buf == p) {
                fprintf(stderr, "format error <%s>\n", buf);
                return -1;
        }

        /* Some other code */

        memset(buf, 0, sizeof(buf));

        /* Fill buf with a string */

        v = strtoul(buf, &p, 16);
        p = NULL;      // <--- This is wrong!!
        if (buf == p) {
                fprintf(stderr, "format error <%s>\n", buf);
                return -1;
        }

The content inside the if's will never be executed, because buf is statically allocated hence it will never be NULL. Of course the issue is the row "p = NULL;". Inside p there should be the pointer to the first invalid character (i.e. not an hexadecimal digit) found in buf. So the condition should evaluate to true if the string does not contain any valid hex number.

This is a trivial error, but the thing that makes it funny is that it has been repeated twice in few rows, probably because of an unfortunate copy & paste operation.

I'm a big fan of the Ctrl+C Ctrl+V sequence, but I know that it can make you lose more time than what you save by not retyping the same thing.

Yin Yang

In this particular case, the error is quite subtle and it can remain unnoticed for years (as actually it did). This is because strtoul() returns zero whenever the string doesn't start with an hexadecimal digit. But zero may be a valid value for further operations.

My suggestion is to always check twice when you copy and paste some code: you can easily replicate unnoticed errors.


Image from Wikimedia Commons (public domain).

Post updated on 2022/06/05.