In a statement like the one above, is there a threat/leak or does it only truncate the string that is loaded into buffer1?Code:char buffer1[10]; char buffer2[10] = "something"; sprintf(buffer1, "with %s", buffer2);
In a statement like the one above, is there a threat/leak or does it only truncate the string that is loaded into buffer1?Code:char buffer1[10]; char buffer2[10] = "something"; sprintf(buffer1, "with %s", buffer2);
You have a buffer overflow. You could avoid it by specifying the width, e.g., "with %4s"
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Yes but the compiler does not complain about it. I don't care if the string is truncated, will it cause any problem?
Buffer overflows yield what the C standard calls "undefined behavior". If code is otherwise correct (syntactically, etc) compilers are not required to complain about code that exhibits undefined behaviour.
Truncating the string is a way to avoid the problem of buffer overflow (assuming you truncate it sufficiently, of course).
The total number of characters written to buffer1, in your example, needs to be 10 or less (and that includes the terminating char with value zero that sprintf() always appends to the end). That means, at most, you can only write 4 characters from buffer2 (which is the reason for the 4 in %4s suggested by laserlight). Write 5 or more characters, and your code has a buffer overrun.
Last edited by grumpy; 01-03-2014 at 05:27 AM.
You can also use snprintf in this situation. If there is not room the string will be truncated. Also, you can make use of the return value of snprintf to see if you "ran out" of space in your 10-byte buffer. Alternatively you can use this to decide how big a dynamically-allocated buffer should be for an arbitrary format string and parameters.
snprintf(3): formatted output conversion - Linux man pageThe functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.
Most compilers will not warn about this. One way to force a complaint to occur is to make use of assert. For example if N is 10
If you accidentally overrun buffer1 inbetween the asserts, technically the behavior is undefined, but with the second assert you have a good chance to catch the problem, since overrunning the buffer will also typically overwrite the final '\0' character.Code:char buffer1[N]; char buffer2[N] = "something"; assert(memset(buffer1, '\0', N)); /* ... */ /* write to buffer1 */ /* ... */ assert(buffer1[N-1] == '\0');
Last edited by c99tutorial; 01-03-2014 at 01:11 PM.