Re: sprintf counterparts?



Hi Norman!

char szBuf[1024];
_snprintf(szBug, 1024, ...);
szBuf[1024-1] = 0;

No, DON'T DO IT LIKE THIS.

You're defeating the purpose of _snprintf by hard coding the size of the string in places where it is not necessary.

What if someone comes along later and decides that allocating 1024 bytes is wasteful and changes only the "char" statement to, say, 256?

This was just an example...

Always try to write code so that values which depend on the compile-time size of a buffer really do use the compile-time size of the buffer.

char szBuf[1024];
/* lots of other stuff here */
_snprintf(szBug, sizeof szBuf, ...);
szBuf[sizeof szBuf-1] = 0;

It also does not work if your "szBuf" was allocated via "new/malloc"...

So again... it was just a example to demonstrate how to use _snprintf and demonstarte that you *must* terminate the string with NUL.

Greetings
Jochen
.



Relevant Pages

  • Re: what is the best way of passing floats into a string
    ... I do not null-terminate as snprintf takes care of this (according to ... But the easiest way to determine the size needed to format a number, ... int length_of_representation(double n,const char* format){ ... I get a nice result of -10.000000 in my char * string. ...
    (comp.unix.programmer)
  • Re: Cannot return values of char variable
    ... - buffer = ... Since you seem to be trying to return a char pointer ... int id = random; ... content is interpreted as a string. ...
    (comp.lang.c)
  • Re: why I can not write to the file after initialize the MFC in a service program
    ... you don't use char, an obsolete data type ... Why do you need an intermedate buffer to write literal strings anyway? ... For example, if AfxWinInit fails, you copy a 45-character string into a ... So you are going to try to initialize MFC EACH TIME THROUGH THE LOOP? ...
    (microsoft.public.vc.mfc)
  • Re: why I can not write to the file after initialize the MFC in a service program
    ... you don't use char, an obsolete data type ... Why do you need an intermedate buffer to write literal strings anyway? ... For example, if AfxWinInit fails, you copy a 45-character string into a ... So you are going to try to initialize MFC EACH TIME THROUGH THE LOOP? ...
    (microsoft.public.vc.mfc)
  • Re: detecting characters on RS232-Interface
    ... read data into string variable ... > splitted at the end of the receive buffer). ... examine the next char in turn. ... When a character ...
    (microsoft.public.vb.general.discussion)