Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf_s problem

Tags:

c++

c

I have a funny problem using this function. I use it as follow:

int nSeq = 1;
char cBuf[8];
int j = sprintf_s(cBuf, sizeof(cBuf), "%08d", nSeq);

And every time I get an exception. The exception is buffer to small. When I changed the second field in the function to sizeof(cBuf) + 1.

Why do I need to add one if I only want to copy 8 bytes and I have an array that contains 8 bytes?

like image 773
Boris Raznikov Avatar asked Sep 09 '09 08:09

Boris Raznikov


People also ask

What is Sprintf_s?

The sprintf_s function formats and stores a series of characters and values in buffer . Each argument (if any) is converted and output according to the corresponding format specification in format . The format consists of ordinary characters and has the same form and function as the format argument for printf .

What is the difference between Sprintf and Snprintf?

The snprintf function The main difference between snprintf and sprintf is that the former takes an argument that specifies the number of characters to write to the character array, whereas the latter does not take such an argument.


2 Answers

Your buffer contains 8 places. Your string contains 8 characters and a null character to close it.

like image 142
xtofl Avatar answered Oct 01 '22 12:10

xtofl


Your string will require terminating '\0' and 8 bytes of data(00000001) due to %08d. So you have to size as 9.

like image 30
GG. Avatar answered Oct 01 '22 12:10

GG.