tags:

views:

243

answers:

3
+2  Q: 

sprintf_s problem

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?

+8  A: 

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

xtofl
So I need to increae the size of buffer by 1 ?
Roman Dorevich
Yes. 1 is exactly the size of the null terminator. In my code I even literally write `char cBuf[8+1]` to emphasize the fact that I need place for this extra character.
xtofl
I've used `char[sizeof("00000000")]`.
MSalters
+1  A: 

All sprintf functions add a null to terminate a string. So in effect your string is 9 characters long. 8 bytes of text and the ending zero

Toad
So I need to increae the size of buffer by 1 ?
Roman Dorevich
+1  A: 

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

GG