Re: Is this C style function well written and thread safe?
<jeff_j_dunlap@yahoo.com> wrote in message
news:1189609812.428625.150200@g4g2000hsf.googlegroups.com...
: Dear C++ Users:
:
: I alwasy use std::string and avoid char buffers but last night I
: wanted to see if I could make a C style function that would be thread
: safe.
:
: For me, it was a good learning experience since my C/C++ knowledge is
: limited but I do understand threading issues due to prior Delphi
: experience.
:
: In the following function, pleas assume that the Date object is well
: written. What I really want to know is if my char buff is being
: handled safely.
:
:
: void fbDateToStr( const IBPP::Date &d, char *buff )
: {
: if ( d < IBPP::MinDate || d > IBPP::MaxDate )
: {
: strcpy(buff, "");
Ok, or you could just write: *buff = '\0';
: }
: else
: {
: int iMonth=0, iDay=0, iYear=0;
: d.GetDate(iYear, iMonth, iDay);
: sprintf(buff, "%d/%d/%d", iMonth, iDay, iYear);
This call could cause an unexpected buffer overfow
if iYear/iMonth/iDay has an out-of-range value
(e.g. if year somehow gets to be 12345678 instead of 2007).
Your platform probably provides a call such as
snprintf or slprintf or sprintf_s, which are
all safer by allowing to restrict output size.
[ you can then also more safely rely on a "tight fit" buffer ]
Also, if you want the output to include leading
zeroes (01/01/1999), you'll want to use the following
format string: "%02d/%02d/%04d"
: }
: }
:
:
: USAGE:
: char buffer[15];
: fbDateToStr(dtInitialContactDt, buffer);
:
: RETURNS:
: MM/DD/YYYY or if date is invalid, a blank string
:
: NOTES:
: Initially, I thought of creating a static buffer within the function
: instead of passing a buffer as this function currently is doing, but
: doing so would have been thread-unsafe since the buffer would now be
: visible/editable by all threads.
Indeed: making sure that a buffer of the right size is provided
is a key issue when using C-style character buffers.
Some ideas for dealing with fixed-size char buffers in C++:
You can take a fixed size char array by reference:
void fbDateToStr( const IBPP::Date &d, char (&buff)[11] )
This will check that the caller provides an array of the
exact desired size.
You could also return a character array encapsulated
into a struct. For instance, using something like
boost::array:
array<char,11> fbDateAsStr( IBPP::Date const& d )
{
array<char,11> ans;
...
return ans;
}
hth-Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com