Derek Johnson
Derek Johnson

Reputation: 737

Writing to file if sprintf() buffer is overflow?

let's say I have this simple code:

#include <stdio.h>
#define BUFFER_LEN 10
int main()
{
    char buffer[BUFFER_LEN];
    sprintf(buffer, "Oh noes, it's too long! What can I do?");

    return 0; 
}

Obviously it won't work since the buffer is too small to contain string. I know that there are different functions that can be used, and different memory handling for buffer. However my question is: is it possible to somehow check if buffer is overflown, and if so open text file and write to it, instead of putting it inside of the buffer.

Upvotes: 1

Views: 602

Answers (1)

iBug
iBug

Reputation: 37267

Sure. Check the output length with snprintf() first:

int len = snprintf(NULL, 0, "Oh noes, it's too long! What can I do?");

And then you have len which you can do necessary evaluation and comparison.

From CppReference:

Return value

snprintf(): number of characters (not including the terminating null character) which would have been written to buffer if bufsz was ignored, or a negative value if an encoding error (for string and character conversion specifiers) occurred

So it will write a limited number of characters to the buffer (specified by the 2nd argument), and return the length of the full data that would have been written, which makes it a good function for string length evaluation.

Upvotes: 6

Related Questions