What’s Wrong With This Code?

C Add comments

This code sample is adapted from a bug in a third-party library which I just fixed:

int getNumFields(char* buf, int bufLen)
{
    const int fieldHeaderSize = 32;
    int count;

    for (count = 0; buf[count] != 0xD; count += fieldHeaderSize)
    {
        // No 0xD found in buffer, return failure
        if (count >= bufLen)
            return -1;
    }

    return (count / fieldHeaderSize);
}

What’s wrong with this code?

The problem is that if the loop does not find any 0xD characters in buf, it will read past the end of buffer before checking the range violation. I rewrote the code to look like:

int getNumFields(char* buf, int bufLen)
{
    const int fieldHeaderSize = 32;
    int count;

    for (count = 0; count < bufLen && buf[count] != 0xD; count += fieldHeaderSize)
    {
    }

    // No 0xD found in buffer, return failure
    if (count >= bufLen)
        return -1;

    return (count / fieldHeaderSize);
}

Nice job dbt in figuring it out in no time.

Comments are closed.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in