Question

The static analysis tool we use is flagging C code similar to the following as a critical buffer overflow.

#define size 64
char  buf [size + 1] = "";
memset (buf, 0, size + 1);

The tool's error message is: Buffer Overflow (Array Index Out of Bounds): The array 'buf' size is 1. Array 'buf' may use the 0..64 index.

Is this legitimate? Does the assignment of the character array to the empty string really result in its length being reduced to a single byte, as if it were defined as char buf [] = "";?

Was it helpful?

Solution

Assigning "" to buf[size+1] does not reset the size of buf, but it is pointless, because it is duplicating a small portion of what the subsequent memset does (and it confuses your static analysis tool - you might want to file a bug report against it).

OTHER TIPS

Aside from the fact that char buf[size+1] won't compile because size is a runtime value, assuming you could build buf as a size 65 array, then memset(buf, 0, 65) would not be an overflow.

Odds are your tool is confused by your syntactic issues.

[Edit: more information]

Based on comments to my original post, I suggest the following:

#define size 64
char buf[size+1];
strcpy(buf, "");
memset(buf, 0, size+1);

I believe Rob Kennedy is correct; your tool is using the empty string initializer value as the array size rather than the static array declaration.

It is not a buffer overflow.

This is probably a cleaner way to do it. Certainly it takes less lines of code.

#define size 64
char buf[size + 1] = {0};

It's legal - the buffer is big enough. The tool is warning you that size_t might be bigger than int and trying to use it as indexer may lead to unpredictable results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top