BigDongle
BigDongle

Reputation: 253

Buffer is accessed out of bounds in cppcheck

Code can be compiled and result is fine. But cppcheck will report an error of it.

#define BUF_SIZE     1024
#define MAX_LENG     80

static unsigned char path[MAX_LENG];
unsigned char file_buf[BUF_SIZE*2];

memset(file_buf, 0, sizeof(file_buf));
strcpy(file_buf, "KID ");
strncat(file_buf, &path[strlen(path)-12], 10); //error this line

I tried a few time, and still cannot find the reason. Anyone can give me some hints ?

Thanks all the answers.

but I have more questions: If this is a fatal error , why compiler passed and result is what I want ? Under what condition it will have trouble ?

There is any alternative way to realize it ?

And if I changed it into

strncat(file_buf, &path[strlen(path)-12], 5);

cppcheack error will disappear. Why?

Upvotes: 0

Views: 687

Answers (2)

Gerhardh
Gerhardh

Reputation: 12404

You access an array with a too large index:

static unsigned char path[MAX_LENG];

Being static it is initialized to zeroes. This means strlen(path) will return 0.

strncat(file_buf, &path[strlen(path)-12], 10);

Here you subtract 12 which would be -12 but as strlen returns an unsigned value the resulting index is SIZE_MAX-12 which is clearly out of bounds.

Upvotes: 2

This here buffer:

static unsigned char path[MAX_LENG];

Is static, and therefore zero initialized. The first character is 0 when this code is first executed. As such strlen(path) is going to return (size_t)0. Subtract 12 from that and you get a very large unsigned number due to modular arithmetic, a number most definitely larger than 1024.

Upvotes: 3

Related Questions