sprintf
is declared as int sprintf(char *str, const char format, ...); char* str
is the buffer to which the output will be written, however malicious users might put more to that buffer than the sizeof that buffer therefore one can also use snprintf
which includes a parameter that contains the size of the output buffer so bufferoverflows will not happen. What you should note it returns the number of bytes written, therefore you cannot assign it to a char or char[].
const char* foo = "foo";
static char end[BUFSIZE];
snprintf(end, BUFSIZE, ""%s_bar", foo);
I prefer to use snprintf
for it doesn't as easily result in a buffer overflow which is a security error. Now it can atmost print BUFSIZ
characters to end
you can look if the concatenation succeeded if snprintf returns strlen("s_bar") + strlen("foo");
What you can also do is:
char end[BUFSIZE] = "foo_";
strncat( end, "_bar", BUFSIZ);
which is perhaps more what you like.