2 Answers
2

The code under /* test 1 */ doesn't print anything because the vsnprint() function doesn't print to stdout; it just writes its output into the provided buffer.

It's pure luck if the code didn't crash, though, because the line:

if ((logbuf = calloc(0x0, LOGBUFFERSIZE))== NULL)

actually tells calloc() to allocate 0 bytes of memory. Because of this, I don't think it's guaranteed that the memory logbuf points at is zeroed either -- so not only is your buffer zero bytes long, but calling strlen() on it could crash or give you an invalid result.

Also, the second argument to vsnprint() is supposed to be the size of the buffer, that is the size you've allocated for logbuf, not the length of any string already in it; it's to limit the number of bytes written to the buffer to avoid a buffer overrun.

So to get everything working, you need to change:

if ((logbuf = calloc(0x0, LOGBUFFERSIZE))== NULL)

..to..

if ((logbuf = calloc(1, LOGBUFFERSIZE))== NULL)

..to allocate space for 1 item of LOGBUFFERSIZE bytes. And also change:

(void) vsnprintf(logbuf, strlen(logbuf), fmt, va);

..to..

vsnprintf(logbuf, LOGBUFFERSIZE, fmt, va);

..to pass it the size of your buffer and remove the useless (void) cast. And also add a line to print logbuf, such as:

Will never format anything, because logbuf is all zeros (having been allocated by calloc, and so strlen will return zero, which makes vsnprintf never format anything because you told it to print at most zero characters.

Even after fixing that problem, you still won't get anything printed because vsnprintf doesn't print. It puts the result into logbuf, but you never print logbuf.
–
Raymond ChenOct 14 '11 at 2:45

1

Are you out of your mind? Changing it to malloc was not the solution--now you are using uninitialized memory. You need to pass LOGBUFFERSIZE as the second argument rather than strlen(logbuf).
–
John ZwinckOct 14 '11 at 2:49

How is it incorrect? I will readily admit that it is incomplete, as I see now there were actually many problems with the code, but if I said something actually wrong I would like to know what.
–
John ZwinckOct 14 '11 at 12:24