looking for statefull snprintf

C

CBFalconer

Chris said:
[someone -- I cannot quite untangle the attributions at this point --
wrote]
bufindex += snprintf(buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);

This code is obviously wrong: the first argument needs to be
&buffer[bufindex] (or equivalent).

I'm the culprit - I recognize my own mistake. I think the -1 is
unnecessary too, but harmless.
.... snip ...

You only need snprintf() if the format is complicated, in which
case, you usually need the "restart from beginning" behavior.

Precis - this is all about a method of filling a buffer with no
overruns, and dumping when necessary.

So, since we can overwrite the tail end of the buffer at any time,
we can obviously simplify things to:

retry: newdex = snprintf(&buffer[bufindex],
sizeof(buffer) - 1 - bufindex,
format, whatever);
if ((newdex + bufindex) > sizeof buffer) {
/* overflow occured */
buffer[bufindex] = '\0';
flushbuffer(buffer);
bufindex = 0;
goto retry
}
bufindex += newdex;

eliminating the up front test. I am too lazy to look for simple
elimination of the goto. Now snprintf no longer needs the behavior
for length 0 and a NULL string, but it still needs to meet
specifications for attempted overrun. I suspect that substitutine
the clause:

if ((newdex < 0) || ((newdex + bufindex) > sizeof buffer))

would handle the prevalent library failures also.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top