Eric Lilja said:
Hello, I'm a novice C++ programmer and now I have the task of converting
a number of C++ functions to C. Some of the functions I'm converting takes
a
parameter
of type reference-to-std::string that stores verbose error information if
an
error occurs in
the function.
How should I implement that in C? A pointer to a fixed-size array of chars
runs the risk
of overflowing. Having the function take a char** and allocate memory as
necessary
seems a poor idea too...reallocations might be needed and the user must
remember that
deallocate.
Any suggestions?
I assume that you need to dynamically generate the verbose error
information; otherwise just taking a char** and pointing the char*
it points to at a string literal will work:
--------
if(errstring)
*errstring="Verbose error information";
--------
If you can put a reasonable upper bound on the length of the information
you need to return, you can statically allocate a buffer and return a
pointer to that:
--------
if(errstring)
{
/*static means it will stick around after we return, which is what we
want.
Note that this also means the caller will need to extract any
useful information before calling this code again, as another
error will overwrite it.
*/
static char errbuf[BIG_ENOUGH];
/*Using snprintf just to be paranoid
Note that snprintf is new in C99. It's also available as a GNU
extension, with different return value semantics (return value
isn't used here, so the difference won't cause problems).
If snprintf isn't available, check your maximum format length more
carefully and use sprintf.
*/
snprintf(errbuf,BIG_ENOUGH,"Verbose error info: foo is %d, bar is
%g",foo,bar);
*errstring=errbuf;
}
--------
If you don't have a way to know at compile time how long the string
can get, you'll need to somehow allocate memory for it at run time.
Keeping a static pointer to that buffer in your code (similar to just
keeping a static buffer) will let the caller not need to worry about
deallocating it, as you can recycle it (resizing it if necessary) the
next time you need it.
dave
--
Dave Vandervies (e-mail address removed)
I'd better change my domain then; I'm in .net, and I'm physically
somewhere on the Net; it's far too easy for folks to guess *that*.
--Anthony de Boer in the scary devil monastery