1

I'm using snprintf() to write string into a buffer.

#define MAXLEN 256
char line[MAXLEN];
char buf[MAXLEN];

snprintf(buf, sizeof(buf), "Hi%s", line);

When compiling, it shows warning

directive writing up to 256 bytes into a region of size 254

Any better way to solve this? I don't want to use malloc(...) or similar dynamic allocating function.

code_worker
  • 384
  • 3
  • 16
  • `Any better way to solve this?` _How_ do you want to solve it? In the case `line` is a string of 255 characters, do you want to print only 253 of them? – KamilCuk Apr 19 '21 at 14:12
  • @KamilCuk Or how should I modify it? e.g. Allocating small 'char line' is better? – code_worker Apr 19 '21 at 14:15
  • Making sizeof(buf) larger or sizeof(line) smaller would do it, I think. – Jeremy Friesner Apr 19 '21 at 14:17
  • 2
    The compiler is warning you that the number of elements in `line` is too big for the output buffer. Of course, the size of `line` doesn't tell you how many characters are actually in it; that's determined by where the terminating nul is. That's determined by the length of the string, which the compiler has no way of knowing. In short: that warning is nonsense. You can either work around that nanny warning or turn it off. – Pete Becker Apr 19 '21 at 14:17
  • 1
    I'm asking what the result you _want_ to have? In case `line` is a long string of 255 characters, what do you _want_ to happen then? Should `buf` be `Hi<253 characters from line>`? Or do you want `buf` to be `Hi`? If the first, silence the warning, if the second, increase buf size. – KamilCuk Apr 19 '21 at 14:46

1 Answers1

0

I want the second result.

Then you have to make sure the destination buffer is long enough to hold it. For example:

char line[MAXLEN];
char buf[MAXLEN + 2];

that way buf can hold a whole line and also two "Hi" characters.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111