This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: Debug mode output broken
On Fri, Aug 06, 2004 at 02:46:18PM +0200, Paolo Carlini wrote:
> Jonathan Wakely wrote:
>
> >First of all, please note that __n is not the buffer size here, it's the
> >length of the word to be copied. snprintf() is not used to prevent __buf
> >from being overflowed, it's used to prevent the whole of __s being copied.
> >
> >
> Please have a look to the whole debug.cc: most of the times, according
> to a very
> common practice, snprintf is passed exactly __bufsize.
>
> There is only *one* case, _M_print_string, where the second parameter of
> snprintf
> is used for the other purpose that you are emphasizing above.
yes, sorry - when I said
>> When that code runs __n is ALWAYS < strlen(__s)
I meant when called from _M_print_string(), as I've only been following
that code path and haven't looked at any other uses of _M_format_word()
yet. Again, sorry for being unclear.
> That's why we have a bug: someone replaced snprintf (when not available)
> with
> sprintf considering only the former uses of _M_format_word. We have to deal
> correctly with the exception represented by _M_print_string.
Instead of using _M_format_word() in _M_print_string() why don't we just
copy the desired chars into the buffer directly? The "formatting" being
done by _M_format_word() is only "%s" anyway.
Something like this:
- assert(__end - __start + 1< __bufsize);
- _M_format_word(__buf, __end - __start + 1, "%s", __start);
+ const ptrdiff_t __len = __end - __start;
+ assert(__len + 1 < __bufsize);
+ std::strncpy(__buf, __start, __len + 1);
+ __buf[__len] = '\0';
This doesn't change the fact that _M_format_word() is unsafe when not
using C99.
jon
--
"All that we are is the result of what we have thought;
it is compounded of our thoughts, made up of our thoughts."
- Dhammapada, Verse I