Re: style question,itoa



moi schrieb:
On Thu, 24 Jan 2008 21:02:12 +0100, Syren Baran wrote:

Frank Cusack schrieb:
Good to know you know that i will have an easier time reading my code
when using functions i wrote that behave as i wanted to. I didnt know
that yet.
an all too common error to assume

a) no one else will ever read your code. b) you will remember how any
function behaves.
I learned b) the hard way a long time ago. Thats why i document the
functions. That way they will not only "behave as i wanted to", but also
as i document them.
admittedly in this case it's rather trivial.
Yupp, but anyway that file will contain the notice "All functions below
that return a char* require the caller to free the char*."
-frank

For this kind of formatting-functions the snprintf() kind of interface is
perfect: *) it cannot overrun the buffer (once coded correctly)
*) if it would: it returns a negative value.
*) if it succeeds, it returns the amount written,
vs.
*) it cannot overrun the buffer (it malloc's a sufficient buffer)
*) it wont fail if the memory can be alloc'd. [1]
*) it succeeds and returns the char*

such that buffer[return_value] == '\0'; which makes is easy to fill the buffer in multiple calls, and without excess copying.

Utility functions, returning malloc()ed chunks need return value testing by the caller.
Oehm, why?
The snprintf() method does so also, but (on failure) it does *not* need to free() the preceding chunks, which means it is shorten and less error prone.
Ok, but what do i do if i check the error condition and figure out i need a larger buffer anyway? Allocate a new buffer? In that case i can just as well have the utility function allocate the buffer for me, right?

YMMV,
AvK

[1] Checking every small malloc is the logical inverse of calling the lottery service every day asking if i have won even though i didnt get a ticket. Sure somebody may have accidently written my name on the ticket and won, but its not likely.

.



Relevant Pages

  • Re: style question,itoa
    ... an all too common error to assume ... That way they will not only "behave as i wanted to", ... buffer in multiple calls, and without excess copying. ... does *not* need to freethe preceding chunks, ...
    (comp.unix.programmer)
  • Re: [9fans] C library function that reads up to a newline
    ... Dont' think so, as you need a buffer to keep the line. ... outside Bio that behave similarly? ...
    (comp.os.plan9)
  • Re: Anyone see the error?
    ... Response.OutputStream.Write(buffer, 0, bytes) was the ticket. ... That was the missing piece. ... > and bytes is the number of valid bytes in the array (ie., ...
    (microsoft.public.dotnet.framework.aspnet)