An̲̳̳drew
An̲̳̳drew

Reputation: 13892

Is this really a buffer overflow?

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 [] = "";?

Upvotes: 3

Views: 3652

Answers (4)

EvilTeach
EvilTeach

Reputation: 28882

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};

Upvotes: 4

dave-holm
dave-holm

Reputation: 358

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).

Upvotes: 5

Randolpho
Randolpho

Reputation: 56448

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.

Upvotes: 12

sharptooth
sharptooth

Reputation: 170559

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.

Upvotes: 0

Related Questions