0

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?

orbitcowboy
  • 1,438
  • 13
  • 25
BigDongle
  • 253
  • 2
  • 10

2 Answers2

3

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

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.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • @M.M Since the number circle the actual index is -12, if `strlen` returns zero. Valid array indices are positive numbers, but it's actually an access *before* the array. – harper Dec 13 '18 at 07:30
  • @harper no it isn't. – M.M Dec 13 '18 at 07:35