Is this really a buffer overflow?

The static analysis tool we use puts C code similar to the following, like a critical buffer overflow.

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

Tool error message: Buffer overflow (array index out of bounds): The size of the buf array is 1. The buf array can use index 0..64.

Is it legal? Does assigning an array of characters to an empty string really result in its length being reduced to one byte, as if it were defined as char buf [] = "";?

+3
source share
4 answers

"" buf [size + 1] reset buf, , , memset ( - ).

+5

, char buf [size + 1] , , , buf 65, memset (buf, 0, 65) .

.

[: ]

, :

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

, ; , .

+12

.

This is probably a cleaner way to do this. Of course, this takes less lines of code.

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

This is legal - the buffer is large enough. The tool warns you that size_t may be larger than int, and tries to use it as an indexer, which can lead to unpredictable results.

0
source

Source: https://habr.com/ru/post/1703298/


All Articles